Tengo un script para Google Analytics, y en este script creo un condicional distinguiendo la clave de Google Analytics para desarrollo y producción. He realizado las siguientes condiciones y el script también se ha generado como se desea. Pero hay un error Uncaught (in promise) ReferenceError: gtag is not defined
, ¿por qué puede suceder así?
$(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); } }