Thursday, February 27, 2025
HomeAnalytics#GTMTips: Add A Load Listener To Script Elements

#GTMTips: Add A Load Listener To Script Elements


One of the challenges in working with Google Tag Manager (or any JavaScript-based platform for that matter) is what to do with race conditions. A race condition emerges when you have two resources competing for execution in the browser, and there is a degree of unpredictability to which “wins” the race.

A prime example is working with jQuery. It’s one of the most popular JavaScript libraries out there, and websites utilize it for a multitude of things, many useful for Google Tag Manager, too. For example, jQuery trivializes asynchronous HTTP requests and DOM traversal, both of which can cause headaches to GTM users.

However, since jQuery is often, and should often be, downloaded asynchronously, there’s the risk that jQuery hasn’t loaded yet when GTM starts executing your tags. Thus we need some mechanism to let Google Tag Manager know when an asynchronously downloaded or requested resource has become available.


X


The Simmer Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!

Tip 66: Add a load listener to script elements

There are two ways you can go about this. The first one is to use a Custom HTML tag, and then fire a dataLayer.push() once the resource has completely loaded. The second way is to use tag sequencing, and tell GTM that the setup tag (where you load the script) has completed by using the internal onHtmlSuccess() method. But I’m getting ahead of myself.

dataLayer.push() in the load listener callback

The first method is to create a Custom HTML tag that fires as early as possible. So you’d want to add the All Pages trigger to it, so that it fires as soon as the GTM container has loaded.

At this point it’s important that you do not load the script by simply adding the

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments

Skip to toolbar