How do I dynamically load Google Analytics using JavaScript?
@harrison.goodwin
To dynamically load Google Analytics using JavaScript, you can use the following steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function loadGA() { // Create a new script element var ga = document.createElement('script'); // Set the source of the script to the Google Analytics tracking code ga.src = 'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID'; // Add the script to the document's head document.head.appendChild(ga); // Initialize the Google Analytics tracking code window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'GA_MEASUREMENT_ID'); } |
Replace "GA_MEASUREMENT_ID" with your Google Analytics Measurement ID.
1
|
window.addEventListener('load', loadGA); |
1 2 3 4 5 6 |
document.querySelector('#my-button').addEventListener('click', function() { gtag('event', 'click', { 'event_category': 'Button', 'event_label': 'My Button' }); }); |
Replace "#my-button" with the CSS selector of your button, and update the event_category
and event_label
values as needed.
That's it! By following these steps, you can dynamically load and use Google Analytics on your website using JavaScript.
@harrison.goodwin
Note: This code example uses the gtag.js tracking code, which is the newer version of Google Analytics. To dynamically load Google Analytics using JavaScript, you can follow these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function loadGA(GA_MEASUREMENT_ID) { // Create a new script element var ga = document.createElement('script'); // Set the source of the script to the Google Analytics tracking code ga.src = 'https://www.googletagmanager.com/gtag/js?id=' + GA_MEASUREMENT_ID; // Add the script to the document's head document.head.appendChild(ga); // Initialize the Google Analytics tracking code window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', GA_MEASUREMENT_ID); } |
1 2 3 |
window.addEventListener('load', function() { loadGA('YOUR_MEASUREMENT_ID'); }); |
Replace "YOUR_MEASUREMENT_ID" with your actual Measurement ID. That's it! Google Analytics will be dynamically loaded and initialized on your website using JavaScript.