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

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

    This will work if you divide the script into 2 scripts the same way Google Analytics has divided the traditional script into 2 script tags.

    0 讨论(0)
  • 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');

    0 讨论(0)
提交回复
热议问题