Right here’s a fast tip in response to a question in Twitter by Riccardo Mares. By making a small change to the Google Tag Supervisor container snippet, you’ll be able to have the <script>
component generated by the snippet notify the web page as quickly because the Google Tag Supervisor library has downloaded.
What you do with this data is as much as you. In case you are working instantly with the google_tag_manager
interface, for instance, it’d make sense to not act till the interface has been established.
X
The Simmer E-newsletter
Subscribe to the Simmer publication to get the most recent information and content material from Simo Ahava into your e mail inbox!
Tip 78: Notify the web page when the GTM container has loaded
You could add the next code into the container snippet, instantly after the +i+dl;
and instantly earlier than the f.parentNode.insertBefore
.
j.addEventListener('load', perform() {
var _ge = new CustomEvent('gtm_loaded', { bubbles: true });
d.dispatchEvent(_ge);
});
Thus the modified container snippet would appear like this:
(perform(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.begin':
new Date().getTime(),occasion:'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', perform() {
var _ge = new CustomEvent('gtm_loaded', { bubbles: true });
d.dispatchEvent(_ge);
});
f.parentNode.insertBefore(j,f);
})(window,doc,'script','dataLayer','GTM-XXXXX');
Now, when the Google Tag Supervisor container has been downloaded from Google’s servers, the load listener will dispatch a brand new browser occasion named gtm_loaded
.
If you wish to construct a hook for this occasion, you need to use the addEventListener()
methodology, once more:
if (!!window.google_tag_manager) {
// Google Tag Supervisor has already been loaded
doSomethingWith(window.google_tag_manager);
} else {
window.addEventListener('gtm_loaded', perform() {
// Google Tag Supervisor has been loaded
doSomethingWith(window.google_tag_manager);
});
}
On this instance, the code first checks if GTM has already been loaded. If it hasn’t, it creates a brand new listener on the window
object that waits for the gtm_loaded
occasion to bubble as much as it. As quickly because the Google Tag Supervisor library has been downloaded and initialized, the occasion is dispatched and the listener for gtm_loaded
will go off.