How to load gtag.js (google analytics) dynamically in javascript?

by herminia_bruen , in category: Third Party Scripts , 13 days ago

How to load gtag.js (google analytics) dynamically in javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 12 days ago

@herminia_bruen 

You can dynamically load gtag.js (Google Analytics) in JavaScript by creating a script element and appending it to the document head. Here is an example code snippet:

1
2
3
4
5
6
7
8
function loadGoogleAnalytics() {
  var script = document.createElement('script');
  script.async = true;
  script.src = 'https://www.googletagmanager.com/gtag/js?id=YOUR_GA_TRACKING_ID';
  document.head.appendChild(script);
}

loadGoogleAnalytics();


Make sure to replace YOUR_GA_TRACKING_ID with your actual Google Analytics tracking ID before implementing the code. This will load gtag.js dynamically on the page and start tracking analytics data for your website.