Lazy-load scripts in Google Tag Manager

Analytics with Ottimo

Introduction
Account setup
Collections
Why we built Ottimo
Release notes

Learning

Resources

Content Strategy Quickstart

Contact us

Lazy-load third-party scripts in Google Tag Manager

Learn how to lazy-load third-party scripts in Google Tag Manager and improve your site's speed.

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>

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.

image

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.

image

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

image
icon
You might find our newsletter helpful

Everything we have to say on SEO, content performance, and content analytics – in convenient email form.

super-embed:<div class="klaviyo-form-XshxEW"></div>

(Having doubts? Here's a recent issue.)