Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

193
Views
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);
  }
}
7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.