Search code examples
javascriptcookiesgoogle-analytics

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


I am trying to block google analytics in javascript when a user don't want to get cookies.

if (want_cookie != "no"){
   /* load google analytics script */
 }

But I didn't find how to load this script in javascript ...

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXX');
</script>

Solution

  • Try something like this:

        if (want_cookie != "no"){
            var newScript = document.createElement("script");
                newScript.type = "text/javascript";
                newScript.setAttribute("async", "true");
                newScript.setAttribute("src", "https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX");
                document.documentElement.firstChild.appendChild(newScript);
    }
    

    So what I did is after checking if user agree on cookies dynamically create script element and append it to page.