Example: Google Tag Manager
As you're asking for user's consent first, you should only load in Google Tag Manager after the user has consented to it.
The below example demonstrates what thi looks like. It's recommended to hook into both the loaded
event & the consented
event so GTM is initialised both upon page load & when the user updates their consent.
1<script 2 async 3 src="https://www.googletagmanager.com/gtag/js?id=G-SOMETHING" 4></script> 5 6<script> 7 gtag("js", new Date()); 8 gtag("config", "G-SOMETHING"); 9 10 function enableGoogleTagManager() {11 gtag("consent", "update", { analytics_storage: "granted" });12 13 let gtmBody = document.createElement("noscript");14 gtmBody.setAttribute("id", "gtm-noscript");15 16 let gtmIframe = document.createElement("iframe");17 gtmIframe.setAttribute(18 "src",19 "https://www.googletagmanager.com/ns.html?id=GTM-SOMETHING"20 );21 gtmIframe.setAttribute("height", 0);22 gtmIframe.setAttribute("width", 0);23 gtmIframe.setAttribute("style", "display:none;visibility:hidden");24 25 gtmBody.appendChild(gtmIframe);26 document.body.prepend(gtmBody);27 }28 29 cookieNotice.on('loaded', (groups) => {30 if (groups.find(group) => group.slug === 'group_statistics') {31 enableGoogleTagManager();32 }33 });34 35 cookieNotice.on("consented", (group) => {36 if (group.slug === "group_statistics") {37 enableGoogleTagManager();38 }39 });40 41 cookieNotice.on("revoked", (group) => {42 if (group.slug === "group_statistics") {43 // Revoke Google Tag Manager...44 }45 });46</script>
Note: In some EU countries (Austria, Holland, France, Italy), Google Tag Manager / Google Analytics has been declared illegal. If you have users in any of these countries, you are breaking the law simply by using it. Look into something like Fathom Analytics, a privacy-focused analytics service. You won't even need this addon if it's the only third-party script you're using.