Javascript 使用来自外部 JS 文件的 Google Analytics 异步代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3263818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Google Analytics asynchronous code from external JS file
提问by NeilD
I'm trying to add the asynchronous version of the Google Analytics tracking code to a website.
我正在尝试将异步版本的 Google Analytics 跟踪代码添加到网站。
I'd like to keep the JavaScript in a separate file, and call it from there.
我想将 JavaScript 保存在一个单独的文件中,并从那里调用它。
Here's what I've currently got in my .js file:
这是我目前在 .js 文件中的内容:
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);
And here's what I've got in the <head>tag of my Master page:
这<head>是我的母版页标签中的内容:
<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?
任何想法我需要改变什么?
Thanks, Neil
谢谢,尼尔
EDIT:Ok... After some feedback below, I'm going to add the newcurrent 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.
编辑:好的...在下面的一些反馈之后,我将添加我的 .js 文件的新当前内容。我会保持更新,以便如果/当这个问题得到解决时,它有望帮助其他尝试做类似事情的人。
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();
采纳答案by Brian
Your variable definition var _gaqis 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.
您的变量定义var _gaq在函数内。这意味着它在该函数内是局部范围的,不会在全局范围内存在。Google Analytics 依赖于全局变量_gaq。如果您想将其保留在这样的函数中,请将其引用为window._gaq.
回答by gblazex
You completely miss the point of the asynchronous tracking code. Don't put it in an external file because that's exactly like including the old synchronous GA.
您完全错过了异步跟踪代码的重点。不要将它放在外部文件中,因为这与包含旧的同步 GA 完全一样。
And most importantly don't defer the tracking code to window.onloadas it may fire too late.
最重要的是不要推迟跟踪代码,window.onload因为它可能会触发太晚。
If you use the asynchronous GA just put it in the top of you document in an inline script tag. This is the recommendationon Google Analytics websiteas well.
如果您使用异步 GA,只需将它放在文档顶部的内联脚本标记中。这也是Google Analytics 网站上的建议。
Insert the asynchronous snippet at the bottom of the
<head>sectionof your pages, after any other scripts your page or template might use.
在页面部分的底部
<head>插入异步代码段 ,在页面或模板可能使用的任何其他脚本之后。
回答by Joshua Berkowitz
Honestly I have not read through all these posts since they are rather old. However I recently had the need to add Gtag (google tag manager for analytics tracking) to an old website that was a 1000 static HTML files and (LUCKILY) a the html files had a single include js file for the spry menu bar, like i said very old site! For my purposes I wasn't worried about performance but measuring the traffic so we can migrate it. your case may be different but the below code will work for external js includes of Gtag.
老实说,我还没有通读所有这些帖子,因为它们已经很旧了。但是,我最近需要将 Gtag(用于分析跟踪的谷歌标签管理器)添加到一个旧网站,该网站是一个 1000 个静态 HTML 文件,并且(幸运的是)html 文件有一个用于 spry 菜单栏的包含 js 文件,就像我说很老的网站!出于我的目的,我并不担心性能,而是测量流量以便我们可以迁移它。您的情况可能有所不同,但以下代码适用于 Gtag 的外部 js 包含。
I used this file to load the code below since the above code is for legacy ga.js
我使用这个文件来加载下面的代码,因为上面的代码是针对遗留的 ga.js
//Added Google Anyltics Tag Container Tracking - included here to min rebuilding DOM
function loadGoogleAnalytics(){
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = 'https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
}
loadGoogleAnalytics(); //Create the script
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-1');
//Confirmed with Google tag Assistant

