Is it possible to put Google Analytics code in an external JS file?

后端 未结 8 693
生来不讨喜
生来不讨喜 2021-02-05 02:56
var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");
document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-anal         


        
8条回答
  •  不知归路
    2021-02-05 03:17

    Upload google analytics dynamically:

    function loadGoogleAnalytics(){
        var ga = document.createElement('script'); 
        ga.type = 'text/javascript'; 
        ga.async = true;
        ga.src = 'https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-XX';
    
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    }
    
    loadGoogleAnalytics(); //Create the script  
    
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    
    gtag('config', 'UA-XXXXXX-XX');
    

    Don't forget to replace XXXXXX-XX with your account id.

提交回复
热议问题