Loading Google Analytics script after user consent

I need to load Google Analytics only after users agree to tracking cookies on my site. When I try to inject the tracking script using JavaScript, it doesn’t seem to work properly. The script gets added to the page but no events or page views are being recorded.

Here’s my current approach:

const trackingScript = document.createElement('script');
trackingScript.src = 'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID';
trackingScript.async = true;
document.head.appendChild(trackingScript);

window.dataLayer = window.dataLayer || [];
window.analytics = function() { dataLayer.push(arguments); }

window.analytics('js', new Date());
window.analytics('config', 'GA_MEASUREMENT_ID');

When I put the same code directly in my HTML file, everything works fine. What am I missing when adding it dynamically?

You’re calling dataLayer.push before Google Analytics finishes loading. When you load scripts dynamically, there’s no guarantee gtag exists when your code runs. I hit this exact problem last year. The fix is checking if gtag is actually defined first. Wrap your analytics calls in a function that polls for gtag, or use the script’s load event handler. What worked best for me was initializing dataLayer first, then adding a callback that runs once GA confirms it’s ready. Here’s the thing - just because your script element is in the DOM doesn’t mean the gtag function is available yet. That takes extra time. Also worth noting: ad blockers mess with dynamically loaded GA scripts way more than inline ones. That’s probably why your static HTML works fine but the dynamic version fails sometimes.

The issue is timing. Your analytics code runs before the GA script finishes loading.

You’re creating the script element but immediately trying to use gtag functions that don’t exist yet. The script needs time to download and execute.

Here’s what happens: you append the script, then instantly call analytics functions, but gtag isn’t ready. The script tag exists in DOM, but the actual Google Analytics code hasn’t loaded.

I’d automate this whole consent management flow instead of manually handling script loading and timing issues. I built a similar system that waits for user consent, loads GA properly, and handles all the timing automatically.

The automation watches for consent events, loads scripts in the right order, and makes sure everything fires correctly. No more debugging timing issues or missing events.

This consent-to-analytics workflow is perfect for automation since it’s multiple steps that need to happen in sequence. Set it up once and never worry about script loading order again.

Check out https://latenode.com

you need to wait for the script to load first. try adding an onload event to your trackingScript, and then call your analytics functions inside that. this should fix the tracking issue for you!