0

I am trying to inject Google analytics code dynamically to my dom. My code looks like this

 (function () {
    const head = document.getElementsByTagName("head")[0];

    var myScript = document.createElement('script');

    myScript.setAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=UA-1234567-6');
    head.insertBefore(myScript, head.children[1]);

})();

window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());

gtag('config', 'UA-1234567-6');

I can see https://www.googletagmanager.com/gtag/js?id=UA-1234567-6 getting added to my DOM. But the code below it (starting with window.dataLayer) is not getting executed. How can I solve this issue?

1 Answer 1

3

Try using onload event

(function() {
  const head = document.getElementsByTagName("head")[0];

  var myScript = document.createElement('script');

  myScript.setAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=UA-1234567-6');

  myScript.onload = function() {
    window.dataLayer = window.dataLayer || [];

    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());
    
    console.log('window.dataLayer Executed', window.dataLayer)

    gtag('config', 'UA-1234567-6');
  }

  head.insertBefore(myScript, head.children[1]);

})();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.