简体   繁体   English

在单独的.js文件中使用Google Analytics(分析)的代码是什么?

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

I read somewhere that placing google analytics tracking code in seperate file is not recommended but I have no idea how to use it for my website (there are .php files and .tpl files and if I tried to put it almost everywhere and there was an error or it didn`t track the visitors). 我读过某个地方的文章,不建议将Google Analytics(分析)跟踪代码放在单独的文件中,但是我不知道如何在我的网站上使用它(有.php文件和.tpl文件,如果我尝试将其放置在几乎所有地方,错误或没有跟踪访问者)。

Could anyone tell me which code I should put into separate .js file and in .tpl file so at least the basic functions would work? 谁能告诉我应该将哪个代码放入单独的.js文件.tpl文件中,以便至少可以使用基本功能? Thanks a lot! 非常感谢!

This is the cleanest (using a anonymous auto-executing function): 这是最干净的(使用匿名自动执行功能):

(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);
})();

Then reference in either your head or before end of body via: 然后通过以下方式在您的头部或身体末端引用:

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

you can write google analytics code in separate js file and include that js and call its function - 您可以在单独的js文件中编写Google Analytics(分析)代码,并包含该js并调用其功能-

Suppose, following code is written in mygoogle.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);
    })();
}

then in your php files in header - 然后在标题的php文件中-

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

In onload function of body tag - 在body标签的onload功能中-

function onload(){
loadMyGoogle();
}

I hope you know how you can set onload event in body tag 我希望您知道如何在body标签中设置onload事件

Do not put GA code in .js file instead include html page. 不要将GA代码放在.js文件中,而应包括html页面。

Steps: 1) Open notepad and paste GA code there. 步骤:1)打开记事本,然后在其中粘贴GA代码。 2) Save it as HTML page 3) Include that html before end of head tag 2)将其另存为HTML页面3)在head标签末尾之前包含该html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM