Loading in Wordpress tag manager, and I want to add a setTimeout to load the script 5 seconds later.
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. If a user visits your site for just a few seconds and then leaves, it is called a "bounce" in 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 . You may want to consider other options to whatever problem you're solving before delaying 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
. If javascript is enabled, that tag won't do anything. If javascript is disabled, the setTimeout
won't work so the noscript
tag won't get added. I would just add it to the body
as-is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.