使用来自外部 JS 文件的 Google Analytics 异步代码 [英] Using Google Analytics asynchronous code from external JS file
问题描述
我正在尝试将异步版本的 Google Analytics 跟踪代码添加到网站.
I'm trying to add the asynchronous version of the Google Analytics tracking code to a website.
我想将 JavaScript 保存在一个单独的文件中,并从那里调用它.
I'd like to keep the JavaScript in a separate file, and call it from there.
这是我目前在 .js 文件中的内容:
Here's what I've currently got in my .js file:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function loadtracking() {
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
_gaq.push(['_trackPageview']);
(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);
})();
}
addLoadEvent(loadtracking);
这是我在母版页的 <head>
标签中得到的:
And here's what I've got in the <head>
tag of my Master page:
<script type="text/javascript" src="js/google-analytics.js" ></script>
然而,显然有一个问题,几天后,我没有通过统计!
However, there's obviously a problem as after a few days, I'm not getting stats through!
有什么我需要改变的想法吗?
Any ideas what I need to change?
谢谢,尼尔
好的...在下面的一些反馈之后,我将添加我的 .js 文件的新当前内容.我会保持更新,以便如果/当这个问题得到解决时,它有望帮助其他尝试做类似事情的人.
Ok... After some feedback below, I'm going to add the new current contents of my .js file. I'll keep it updated so that if/when this gets solved, it will hopefully help other people trying to do similar things.
var _gaq = _gaq || [];
function loadtracking() {
window._gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
window._gaq.push(['_trackPageview']);
(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);
})();
}
loadtracking();
推荐答案
你的变量定义 var _gaq
在一个函数内.这意味着它在该函数内是局部范围的,不会在全局范围内存在.Google Analytics 依赖于全局变量 _gaq
.如果您想将其保留在这样的函数中,请将其引用为 window._gaq
.
Your variable definition var _gaq
is inside a function. That means it's locally scoped inside that function and won't exist globally. Google Analytics depends on the global variable _gaq
. If you want to keep it inside a function like that, reference it as window._gaq
.
这篇关于使用来自外部 JS 文件的 Google Analytics 异步代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!