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

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

    @Nikko

    One possible reason is because the GA account was created using the old analytics. So you must use the traditional analytics code ga.js (_gaq.push). I found an incompatibility in using the new analytics.js with the traditional GA account in the GA website. The hits won't appear so I was forced to use the traditional ga.js.

    Also, you may set a callback function to assure the hits are successfully sent, like below:

    //traditional way
    _gaq.push(['_set', 'hitCallback', function() {
      console.log("%c ga.js finished sending pageview data to analytics %s ", "color:black; background: pink", pageviewUrl);
    }]);
    
    //new analytics way
    ga('send', 'pageview', {
                'page': pageviewUrl,
                'hitCallback': function() {
                    console.log("%c analytics.js done sending data. pageview url = %s ", "color: black, background: pink", pageviewUrl);
                }
            });
    

    where pageviewUrl = the url of the site

    Hope that helps!

提交回复
热议问题