Skip to content

Instantly share code, notes, and snippets.

@NickDeckerDevs
Last active July 13, 2022 18:33
Show Gist options
  • Save NickDeckerDevs/1e5c5f3f973cae3d67cb5efecc8211dd to your computer and use it in GitHub Desktop.
Save NickDeckerDevs/1e5c5f3f973cae3d67cb5efecc8211dd to your computer and use it in GitHub Desktop.
lazy load hubspot form
<div class="form-module__form ll"></div>
<script id="form-module__script" charset="utf-8" type="text/javascript" data-src="//js.hsforms.net/forms/v2.js" data-targetclass="form-module__form" data-portal="{{ portalId }}" data-form="{{ module.module_content.form_field.form_id }}" defer></script>
<script>
function getFormData(formScript) {
return {
id: formScript.dataset.form,
portal: formScript.dataset.portal,
targetClass: "." + formScript.dataset.targetclass
}
}
function createForm(formData) {
console.log('prefooter form')
console.log('creating: ', formData)
console.log(hbspt)
setTimeout(() => {
hbspt.forms.create({
portalId: formData.portal,
formId: formData.id,
target: formData.targetClass
})
}, 500)
}
const formScript = document.querySelector('#form-module__script')
console.log(formScript)
const formData = getFormData(formScript)
const target = document.querySelector(formData.targetClass)
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
formScript.src = formScript.dataset.src
console.log('script activate powers target: ', target)
createForm(formData)
observer.disconnect()
}
})
})
observer.observe(target)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment