Dec 6, 2023

Lazy-load scripts in Google Tag Manager

Lazy-load third-party scripts in Google Tag Manager

Google Tag Manager makes it easy to add lots of third-party tracking and analytics to your site. This can be very helpful (sometimes).

But it can also really slow your site down as Google Tag Manager tries to load everying on initial page load.

Here’s a trick that can help. The Javascript below will make it so that a particular script only loads once a visitor has actually interacted with a page. That can put the script loading after your page’s initial render, and after your visitor’s first interaction, which results in improved scores from PageSpeed tests.

<script>
  ['click', 'scroll', 'mousemove', 'touchstart'].forEach(function(e) {
    window.addEventListener(e, firstInteraction, {
        once: true
    });
});
var userInteracted = false;

function firstInteraction() {
    if (!userInteracted) {
        userInteracted = true;
        window.dataLayer = window.dataLayer || [];
        dataLayer.push({
            'event': 'firstInteraction'
        });
    }
}
</script>
 Copy
html

Here’s how to use this tool. First, you’ll want to put it in a new tag. Load this tag wherever you’d like to use the trigger – most likely, you’ll want to have this load on All Pages.

Lazy script loading tag configuration in GTM.

Within the tag, we fire an event called firstInteraction whenever the user does something on the site. We then want to put that event into Google Tag Manager as a custom trigger, so that we can use for other events.

It doesn’t matter what you call the Event name – but don’t call it firstInteraction, since that event is what’s already triggered by the code you added.

This Event, however, happens within Google Tag Manager when firstInteraction fires.

Lazy script loading trigger configuration in GTM.

Then you’ll want to attach it to some third-party Javascript that can fire after the page has loaded.

Attaching 3rd party javascript to custom lazy load trigger in GTM.

We’re *actually* here to help

We’re marketers who love spreadsheets, algorithms, code, and data. And we love helping other marketers with interesting challenges. Tackling the hard stuff together is what we like to do.

We don’t just show you the way—we’re in this with you too.

Background image of a red ball in a hole.