The users of my website needs to give their consent before I can use Google Analytics. Therefor I have to dynamically add the script. But I can't seem to get it to work.
I tried the approaches from this question: Dynamically add script tag with src that may include document.write
Which indeed added the script tag, but Analytics doesn't fire off events and pageviews.
If I add this snippet to my index.html, everything works fine.
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-MYGOOGLEID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
</script>
Any ideas?
This is how I try to add it.
const s = document.createElement('script');
s.setAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=UA-MYGOOGLEID');
s.async = true;
document.head.appendChild(s);
window.dataLayer = window.dataLayer || [];
window.gtag = () => {dataLayer.push(arguments);}
window.gtag('js', new Date());
window.gtag('config', 'UA-MYGOOGLEID');