简体   繁体   English

手动将 setTimeout 添加到谷歌标签管理器

[英]add setTimeout to google tag manager manually

Loading in Wordpress tag manager, and I want to add a setTimeout to load the script 5 seconds later.在 Wordpress 标签管理器中加载,我想添加一个 setTimeout 以在 5 秒后加载脚本。

    echo "<script>(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;
    f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-code');</script>";

second part:第二部分:

<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-code"
        height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>

Be careful with loading GTM late.小心延迟加载 GTM。 If a user visits your site for just a few seconds and then leaves, it is called a "bounce" in Google Analytics.如果用户访问您的网站仅几秒钟就离开了,则在 Google Analytics 中称为“跳出”。 If GTM doesn't load in time to send a page view to Google Analytics, you can have an artificially low bounce rate .如果 GTM 没有及时加载以将页面浏览量发送到 Google Analytics,则您可能会人为地降低跳出率 You may want to consider other options to whatever problem you're solving before delaying GTM.在延迟 GTM 之前,您可能需要考虑其他选项来解决您正在解决的任何问题。

Having said that, here's some code that should work.话虽如此,这里有一些应该可以工作的代码。 :) :)

echo "<script>
var loadGtm = 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;
  f.parentNode.insertBefore(j, f);
}
setTimeout(loadGtm.bind(null, window, document, 'script', 'dataLayer', 'GTM-code'), 5000);
</script>";

As @Eike Pierstorff said, it doesn't make sense to load the noscript tag with setTimeout .正如@Eike Pierstorff所说,使用setTimeout加载noscript标签是没有意义的。 If javascript is enabled, that tag won't do anything.如果启用了 javascript,该标签将不会执行任何操作。 If javascript is disabled, the setTimeout won't work so the noscript tag won't get added.如果禁用 javascript,则setTimeout将不起作用,因此不会添加noscript标记。 I would just add it to the body as-is.我只是将它按原样添加到body中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM