I have a script for Google Analytics, and in this script I create a conditional by distinguishing the key from Google Analytics for development and production. I have made the following conditions and the script has also been generated as desired. But there is an error Uncaught (in promise) ReferenceError: gtag is not defined
, why can it happen like this?
$(document).ready(function(){
let script = $('<script async id="link-ga">', { type: 'text/javascript' });
if(window.location.hostname == 'daruma.co.id'){
script.attr('src', 'https://www.googletagmanager.com/gtag/js?id=MY_LIVE_ID');
}else{
script.attr('src', 'https://www.googletagmanager.com/gtag/js?id=MY_LOCAL_ID');
}
$("head").prepend(script);
})
window.onload = function() {
let s = document.getElementById('script-ga');
let linkGa = document.getElementById('link-ga')
let codeLocal = `window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'MY_LOCAL_ID');`;
let codeLive = `window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'MY_LIVE_ID');`;
try {
if(window.location.hostname == 'live-web.com'){
s.appendChild(document.createTextNode(codeLive));
}else{
s.appendChild(document.createTextNode(codeLocal));
}
linkGa.after(s);
} catch (e) {
if(window.location.hostname == 'live-web.com'){
s.text = codeLocal;
}else{
s.text=codeLive;
}
linkGa.after(s);
}
}