在单独的.js文件中使用谷歌分析的代码是什么

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

本文关键字:谷歌 代码 是什么 单独 js 文件      更新时间:2023-09-26

我在某处读到不建议将谷歌分析跟踪代码放在单独的文件中,但我不知道如何将它用于我的网站(有.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>

在体标的加载功能中 -

function onload(){
loadMyGoogle();
}

我希望您知道如何在正文标签中设置加载事件

不要将 GA 代码放在.js文件中,而是包含 html 页面。

步骤:1) 打开记事本并将 GA 代码粘贴到其中。2)将其另存为HTML页面3)在头标签的末尾包含该html