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

后端 未结 8 703
生来不讨喜
生来不讨喜 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:43

    i got an easy way to do this... Since analytic js is asynchronous it won't give any problem...

    include below code in any js file (Please Note: The code i used is new analytics code provided by google analytics)

    var imported = document.createElement('script');
    imported.src = 'https://www.googletagmanager.com/gtag/js?id=UA-12xxxxxxx-1';
    document.head.appendChild(imported);
    
    
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    
    gtag('config', 'UA-12xxxxxxx-1');

提交回复
热议问题