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

by herminia_bruen , in category: Third Party Scripts , 5 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 5 months 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.

Related Threads:

How to dynamically load javascript file in react.js?
How to send backend page load time(speed) to google analytics?
How to include google analytics in php web service?
How to embed google analytics into google site?
How to disable google tag manager and google analytics?
How to include google analytics in preact?