We add the GA code to an JS file and call it from there. Here's what we've got in the <head> tag:
<script src="/public/tail/tail.js"></script>
Here's what we've currently got in the .js file:
// Global site tag (gtag.js) - Google Analytics
dynamicLoadJs('https://www.googletagmanager.com/gtag/js?id=UA-74793602-1','async');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-849140015');
gtag('config', 'UA-74793602-1', { 'anonymize_ip': true });
However, there's obviously a problem as after a few days, I'm not getting stats through!
Any ideas what I need to change?
The function dynamicLoadJs makes asynchronous call to the network to start downloading the script, but the code which you have written gets executed immediately, even before the JS file would have finished downloading.
What you need is a "callback" which gets triggered after your script has loaded and executed.
So you should effectively have a code like the following:
/*This function will load script and call the callback once the script has loaded*/
function loadScriptAsync(scriptSrc, callback) {
if (typeof callback !== 'function') {
throw new Error('Not a valid callback for async script load');
}
var script = document.createElement('script');
script.onload = callback;
script.src = scriptSrc;
document.head.appendChild(script);
}
/* This is the part where you call the above defined function and "call back" your code which gets executed after the script has loaded */
loadScriptAsync('https://www.googletagmanager.com/gtag/js?id=UA-74793602-1', function(){
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-849140015');
gtag('config', 'UA-74793602-1', { 'anonymize_ip': true });
})
Hope this is conceptually clear as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With