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.
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>
Answer
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM