javascriptappendappendchild

How to append Google Analytics code in head using JS


I am trying to append Google Analytics Script code within head when the UserAgent is not bot(googlebot).

What I am trying:

<script type="text/javascript">
var agent = navigator.userAgent.toLowerCase();
var CheckUA = agent.match(/Googlebot/i);

if(!CheckUA) {
       var scriptTagAnalytics = "***MY GA script CODE***"; 
       document.head.prepend(scriptTagAnalytics);
}
</script>

My Google Analytics Code is:

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

Solution

  • I tested it and it is reflecting in Google Analytics. The only thing is the source code will be visible.

     if(!CheckUA) {
      (function() {
      const head = document.getElementsByTagName("head")[0];
      var myScript = document.createElement('script');
      myScript.setAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=UA-123456789-1');
      myScript.onload = function() {
        window.dataLayer = window.dataLayer || [];
        function gtag() { dataLayer.push(arguments); }
        gtag('js', new Date());
        console.log('window.dataLayer Executed', window.dataLayer)
        gtag('config', 'UA-123456789-1');
      }
      head.insertBefore(myScript, head.children[1]);
    })();