最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Delay loading of Google Tag Manager - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 3

This 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);
发布评论

评论列表(0)

  1. 暂无评论