4

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?

1
  • "dynamicLoadJs" and "async" lead me to believe that you may be calling gtag before the file is loaded. Are you seeing errors in console? Aug 14, 2018 at 3:12

1 Answer 1

2

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.

3
  • Thank you very much, I really appreciate your help!
    – George
    Aug 14, 2018 at 8:54
  • @George Hey, did it work for you? Eager to know. :) You can actually check in Google Analytics "Realtime" section for realtime hits from your users. Aug 14, 2018 at 9:58
  • @MrSponge, How can I put it as an accepted answer? Is there a button or something I missed?
    – George
    Aug 22, 2018 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.