javascripthtmlmod-pagespeed

mod_pagespeed, prevent some inline javascript from beeing moved to page bottom


we use mod_pagespeed and it moves our javscript right before the closing body tag.

But we use some scripts that inserts html (a form) right into the place where our javscript is embedded:

<script charset="utf-8" type="text/javascript" src="//xyz.com/xyz.js"></script>
<script>
  xyz.forms.create({ 
    portalId: '26962234',
    formId: '5ba56a4c-04d0-419a-b82e-eec88c572346ß'
  });
</script>

mod_pagespeed moves the script and our form is now generated into the footer of our website.

Is there a way to prevent mod_pagespeed from moving some javascripts, maybe by setting a class or an id or a data-attribute in the tag?

<script data-modps="dont-move-this">
  xyz...
</script>

Maybe someone has a nice solution for this problem.

Kind regards, Yuri


Solution

  • This looks to be a HubSpot form, and we can use the target attribute in the form embed code to specify the <div> you want to force the HubSpot form to render in by targeting the specific HTML class or ID of that <div>. This way, regardless of where the script lives, the target attribute will be specifying an existing element on the page into which the form will be placed once built.

    Your embed code would end up looking something like:

    <script charset="utf-8" type="text/javascript" src="//xyz.com/xyz.js"></script>
    <script>
      xyz.forms.create({ 
        portalId: '2926962',
        formId: '5ba56a4c-04d0-419a-b82e-e7f9eec88c57',
        target: '.hs-form-1'
      });
    </script>
    

    and then you would have a <div> where you want your form to build with the class or ID you specify in the target attribute of the embed code:<div class="hs-form-1"></div>

    Please ensure that a comma is added right after the formId line so that the embed code is properly formatted. There should be a comma on every line where there is a parameter in the embed code, except for the final parameter.

    More information on customizing the HubSpot Form Embed code can be found here: https://developers.hubspot.com/docs/methods/forms/advanced_form_options

    I hope this helps!