Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

622
Vistas
an Uncaught (in promise) ReferenceError: gtag is not defined occurs when I want to create a dynamic script

enter image description here

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);
  }
}
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda