如何确保在调用 Google Analytics 函数之前加载 Google Analytics?
阅读一篇博客文章后,我想到添加安全代码以确保 Google Analytics 对象在调用其函数之前已完全加载。
典型的 Google Analytics 代码类似于:
var pageTracker = _gat._getTracker("X-UAXXXXX");
pageTracker._trackPageview();
我
pageTracker._addItem( bla bla );
pageTracker._trackTrans();
想到了两个选项来双重确保 _gat 对象在使用前加载:
1)使用 JQuery.ready 调用 _get 函数。例如:
$(document).ready(function() {
var pageTracker = _gat._getTracker("X-UAXXXXX");
pageTracker._trackPageview();
}
或
2) 使用 JavaScript 超时
function checkGat() {
if( gat_is_ready ) {
var pageTracker = _gat._getTracker("X-UAXXXXX");
pageTracker._trackPageview();
} else {
setTimeout('checkGat()', 1000);
}
}
checkGat()
有什么更好的解决方案?为什么?还有其他意见吗?
After reading a blog post, I got the idea to add safety code to ensure that the Google Analytics objects are fully loaded before calling it's functions.
Typicle Google Analytics code goes something like:
var pageTracker = _gat._getTracker("X-UAXXXXX");
pageTracker._trackPageview();
and
pageTracker._addItem( bla bla );
pageTracker._trackTrans();
I have thought of two options to double ensure that the _gat-object is loaded before use:
1) Use JQuery.ready to call the _get-functions. Something like:
$(document).ready(function() {
var pageTracker = _gat._getTracker("X-UAXXXXX");
pageTracker._trackPageview();
}
or
2) Use JavaScript timeout
function checkGat() {
if( gat_is_ready ) {
var pageTracker = _gat._getTracker("X-UAXXXXX");
pageTracker._trackPageview();
} else {
setTimeout('checkGat()', 1000);
}
}
checkGat()
What is the better solution? Why? and any additional comments?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这都是不必要的。只需使用新的 Google Analytics 异步代码即可;它会为你做这件事。
使用此代码,您可以根据需要将跟踪信息存储在 JavaScript 数组(称为 _gaq)中。然后,只有在 ga.js 加载并准备就绪后,它才会执行对 Google Analytics 的调用。换句话说,它会为您完成所有这些工作,而无需编写复杂的循环,并且您永远不会出现导致 JavaScript 错误的竞争条件。
这具有非阻塞的额外好处,因此速度稍快一些。
This is all unnecessary. Just use the new Google Analytics Asynchronous Code; it does this for you.
With this code, you store the tracking information in a JavaScript array (called _gaq) as early in the page as you want. Then, it only executes the call to Google Analytics once the the ga.js has loaded and ready. In other words, it does all of this for you, without needing to write complex loops, and you'll never have race conditions that result in JavaScript errors.
This has the added benefit of being non-blocking and thus slightly faster.