I want to delay loading of GTM based on these conditions:
- When page DOM is fully ready, then after 2 seconds
- When mouse is moved
- When page is scrolled
- When click event is registered
This way initial page load time will not be slowed down, and PageSpeed scores will go up.
In my initial testing I have tried removing the script tag, and then adding it later in the console. However, initial PageView is not registered. None of the other events is neither. If I add the script while the page is still loading, it seems to work.
Question is: How can I delay GTM and when GTM is loaded, it finds the events in dataLayer and submits theese too?
I want to delay loading of GTM based on these conditions:
- When page DOM is fully ready, then after 2 seconds
- When mouse is moved
- When page is scrolled
- When click event is registered
This way initial page load time will not be slowed down, and PageSpeed scores will go up.
In my initial testing I have tried removing the script tag, and then adding it later in the console. However, initial PageView is not registered. None of the other events is neither. If I add the script while the page is still loading, it seems to work.
Question is: How can I delay GTM and when GTM is loaded, it finds the events in dataLayer and submits theese too?
Share Improve this question asked Jun 1, 2020 at 22:17 FooBarFooBar 6,14811 gold badges52 silver badges105 bronze badges1 Answer
Reset to default 3This was my work around:
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
// specifically this line below makes PageView get's properly triggered and fired
script.onload = () => { dataLayer.push({ event: 'gtm.js', 'gtm.start': (new Date()).getTime(), 'gtm.uniqueEventId': 0 }); }
script.src = 'https://www.googletagmanager./gtm.js?id=YOUR-GTM-ID-HERE'
document.head.appendChild(script);