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?