#GTMTips: Check If DOM Ready Or Window Loaded Have Fired
Every now and then I run into a problem which needs some creativity to find a fix. When choosing a course of action, I tend to land first on an extremely complicated solution. However, if I’m patient enough, I manage to whittle it down to something far more manageable and efficient.
In this #GTMTips post, I’ll show you one of these extremely simple solutions to a problem which you might normally overcomplicate. The solution is a very well hidden feature of Google Tag Manager, buried deep in the bowels of the
The Simmer Newsletter
Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!
Tip 42: Check if DOM Ready or Window Loaded have triggered
This tip is very, very simple. Basically, there are two flags in the
google_tag_manager interface, and they are activated first when the “DOM Ready” event takes place, and then when the “Window Loaded” event takes place.
If you didn’t have access to these flags, your remaining options would be something horrible like going through the
dataLayer Array, looking for the gtm.dom and gtm.load, or creating your own listeners for the DOM and window load events. Both have timing issues in Google Tag Manager, and both add extra complexity to a situation which could already be solved using something that is native to Google Tag Manager.
Anyway, you can use these interface flags to make sure your Triggers don’t fire before either one of the page load Triggers have activated. A typical use case would be that you have a slowly loading site, and you don’t want a Trigger to go off before the DOM has completely loaded or all the linked resources (e.g. jQuery) have been downloaded.
This is how it works:
window['google_tag_manager'].dataLayer.gtmDom; // true when DOM Ready has fired window['google_tag_manager'].dataLayer.gtmLoad; // true when Window Loaded has fired
Now you can check if these Variables return true, and use that in the Triggers to establish some order into the chaos of the page load.