Hubspot Tracking Script Async & Defer

Dec 07, 2023
 — by 
Kris Kratz
 in 

A major drawback to the Hubspot Tracking script is that it slows down the initial webpage load time by a second or more.

This collects all of the information for the plugin after it loads.

I found a version of this on corwebvitals.io, but it wasn’t working for my version of Hubspot, so I fixed it.

// Hubspot Forms Defer Script ** FIXED **
// Source: https://www.corewebvitals.io/pagespeed/defer-hubspot-forms
// Original
// Source: https://app.hubspot.com/settings/4449000/analytics-and-tracking/tracking
// Replaced script with the one provided by Hubspot from the form's "share" button.
function hubspot_header() {
   ?>
    <script>
        // override the hbspt functionality while hubspot is loading
        var hbspt = {
            //push form to hubcache queue
            forms: {
                create : function(c) {
                    hubcache.forms.push(c)
                }
            },
        };

        // cache hubspot forms here
        var hubcache = {
            forms:[],
            letsgo : function() {
                for (let i in hubcache.forms){
                    // hubspot is now loaded
                    hbspt.forms.create(hubcache.forms[i]);
                }
            }
        }
    </script>
    <script
            type="text/javascript"
            defer async
            src="//js.hsforms.net/forms/v2.js"
            onload="hubcache.letsgo()">
    </script>

<?php
}
add_action( 'wp_head', 'hubspot_header', 20 );