Here’s a quick tip in response to a query in Twitter by Riccardo Mares. By making a small change to the Google Tag Manager container snippet, you can have the <script>
element generated by the snippet notify the page as soon as the Google Tag Manager library has downloaded.
What you do with this information is up to you. If you are working directly with the google_tag_manager
interface, for example, it might make sense to not act until the interface has been established.
The Simmer Newsletter
Follow this link to subscribe to the Simmer Newsletter! Stay up-to-date with the latest content from Simo Ahava and the Simmer online course platform.
Tip 78: Notify the page when the GTM container has loaded
You need to add the following code into the container snippet, immediately after the +i+dl;
and immediately before the f.parentNode.insertBefore
.
j.addEventListener('load', function() {
var _ge = new CustomEvent('gtm_loaded', { bubbles: true });
d.dispatchEvent(_ge);
});
Thus the modified container snippet would look like this:
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;
j.addEventListener('load', function() {
var _ge = new CustomEvent('gtm_loaded', { bubbles: true });
d.dispatchEvent(_ge);
});
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXX');
Now, when the Google Tag Manager container has been downloaded from Google’s servers, the load listener will dispatch a new browser event named gtm_loaded
.
If you want to build a hook for this event, you can use the addEventListener()
method, again:
if (!!window.google_tag_manager) {
// Google Tag Manager has already been loaded
doSomethingWith(window.google_tag_manager);
} else {
window.addEventListener('gtm_loaded', function() {
// Google Tag Manager has been loaded
doSomethingWith(window.google_tag_manager);
});
}
In this example, the code first checks if GTM has already been loaded. If it hasn’t, it creates a new listener on the window
object that waits for the gtm_loaded
event to bubble up to it. As soon as the Google Tag Manager library has been downloaded and initialized, the event is dispatched and the listener for gtm_loaded
will go off.