You can put it anywhere. I would recommend putting HS lib scripts in the header.
Put it in the header-->
<!--[if lte IE 8]>
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2-legacy.js" async></script>
<![endif]-->
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js" async></script>
Then you need to make sure the scroll function should always come after jQuery lib anywhere in your document.
jQuery(window).scroll(function() {
if (!jQuery('.hbspt-form').length) {
hbspt.forms.create({
portalId: "PORT_ID",
formId: "YOUR_FORM_ID"
});
}
});
And you can easily make dynamic PORT_ID and FORM_ID. Shown below using PHP.
<script>
jQuery(window).scroll(function() {
if (!jQuery('.hbspt-form').length) {
hbspt.forms.create({
portalId: "<?php echo $port_id; ?>",
formId: "<?php echo $form_id; ?>"
});
}
});
</script>