簡體   English   中英

在單獨的.js文件中使用Google Analytics(分析)的代碼是什么?

[英]What is the code to use google analytics in seperate .js file?

我讀過某個地方的文章,不建議將Google Analytics(分析)跟蹤代碼放在單獨的文件中,但是我不知道如何在我的網站上使用它(有.php文件和.tpl文件,如果我嘗試將其放置在幾乎所有地方,錯誤或沒有跟蹤訪問者)。

誰能告訴我應該將哪個代碼放入單獨的.js文件.tpl文件中,以便至少可以使用基本功能? 非常感謝!

這是最干凈的(使用匿名自動執行功能):

(function() {
    var _gaq = window._gaq = window._gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
    _gaq.push(['_trackPageview']);

    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

然后通過以下方式在您的頭部或身體末端引用:

<script type="text/javascript" src="YOUR_GA_CODE_LOCATION.js"></script>

您可以在單獨的js文件中編寫Google Analytics(分析)代碼,並包含該js並調用其功能-

假設以下代碼是用mygoogle.js編寫的

function loadMyGoogle()
window._gaq = window._gaq || [];
    window._gaq.push([ '_setAccount',
            'setaccounthere']);
(function() {
        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl'
                : 'http://www')
                + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    })();
}

然后在標題的php文件中-

<head>
<include script="mygoogle.js">
</head>

在body標簽的onload功能中-

function onload(){
loadMyGoogle();
}

我希望您知道如何在body標簽中設置onload事件

不要將GA代碼放在.js文件中,而應包括html頁面。

步驟:1)打開記事本,然后在其中粘貼GA代碼。 2)將其另存為HTML頁面3)在head標簽末尾之前包含該html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM