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>
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.
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.
Then you’ll want to attach it to some third-party Javascript that can fire after the page has loaded.
We find this can be a helpful way to increase site speed and user experience, two things that will help your website perform in the long run.
Have questions? Reach out - we’d love to help!