How can I lazy load a modal form for better page performance in HubSpot?

Hi all,

I have a custom module with a “Book a Meeting” modal that contains a HubSpot form. The modal is hidden by default (display: none via CSS) and only opens when a user clicks a button.

The problem: even though the modal is visually hidden, the form is loading/fetching on initial page load instead of waiting for the user to click the button. This is hurting my page’s performance metrics (unnecessary network request + JS execution on every page load, even for users who never open the modal).

What I want: The form should only fetch/render when the user actually clicks the “Book a call” button — not before.

Any guidance on the right way to achieve this would be really appreciated. Thanks in advance!

Hey @arjunkhankriyal, I hope that you are well!

Thanks for reaching out to the HubSpot Community! :raising_hands:

I’d love to put you in touch with our Top Experts: Hi @zach_threadint, @Anton and @evaldas do you have suggestions to help @arjunkhankriyal, please?

In the meantime @arjunkhankriyal, I’m sharing these resources that can point you in the right direction:

Thanks so much and wishing you a wonderful day!
Bérangère

Hi @arjunkhankriyal ,

You can achieve this by adding some logic via JavaScript that loads the “v2.js” and the form scripts only when the button is clicked.

Below is a very basic example of how this could look like.

This assumes that the custom module has a form field with internal id (hubspot variable name) “form”, but you can replace it with your own field name.

<!-- module.html -->
<button id="load-form-btn-{{ module.id }}" type="button">Show form</button>
<div id="form-container-{{ module.id }}"></div>

<script>
(function() {
  var btn = document.getElementById("load-form-btn-{{ module.id }}");
  var portalId = "{{ portal_id }}";
  var formId = "{{ module.form.form_id }}";
  var target = "#form-container-{{ module.id }}";

  btn.addEventListener("click", function() {
    btn.disabled = true;

    function createForm() {
      hbspt.forms.create({
        portalId: portalId,
        formId: formId,
        target: target
        // add redirectUrl / inlineMessage if you need response handling
      });
    }

    if (window.hbspt) {
      createForm();
    } else {
      var script = document.createElement("script");
      script.src = "https://js.hsforms.net/forms/embed/v2.js";
      script.onload = createForm;
      document.body.appendChild(script);
    }
  });
})();
</script>

You should be able to customize this to your needs by selecting the appropriate button and form container in your code.

Hope this helps!

Use lazy loading; don’t initialize the HubSpot form on page load. Instead, trigger hbspt.forms.createonly when the user clicks the “Book a Call” button, and use a flag so it only loads once. That avoids unnecessary requests and improves page performance.