Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

626
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda