在闭包中使用 _gaq 异步
在脚本标记中使用时,
var _gaq = _gaq || [];
需要在闭包中支持此操作以添加分析异步请求。
即,
experiment = (function(){
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
var nobody_knows_this_var_is_here = "cant see me";
});
如果 _gaq 尚未定义,那么一旦准备好,它就能够找到该数组来执行推送到它的项目。由于 _gaq var 不是公开的,我猜它不会起作用。有什么解决方法吗?
When using
var _gaq = _gaq || [];
within a script tag what would be needed to support this in a closure to add analytics async requests.
i.e.
experiment = (function(){
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
var nobody_knows_this_var_is_here = "cant see me";
});
if _gaq is not already defined will it be able find this array to perform the items pushed on to it once it is ready. since the _gaq var is not public I'm guessing it won't work. Any workarounds?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以这样做:
如果在全局范围内执行,这就会成功。
You could do something like:
If executed in the global scope this would do the trick.
这是可行的(使用 jQuery 的 document.ready 表示法):
This works (using jQuery's notation for document.ready):
我不知道这是否会帮助其他人寻找答案,但也许会。
我遇到了 _gaq 未定义的问题。我意识到我的 GA 片段位于页面末尾附近,就在结束正文标记之前。正如谷歌现在建议的那样,我将其移至正文标签开始之后的位置。我仍然遇到未定义 _gaq 的问题。将
var _gaq = window._gaq || (window._gaq = []);
位于我的代码顶部,其中的自定义事件帮助解决了我的所有问题,但前提是 Google 代码段位于页面顶部。这对我帮助很大,除了 jQuery 就绪函数之外,我不必将它放在每个单击事件或任何地方的函数中。
I don't know if this will help others looking for an answer, but maybe it will.
I had a problem with _gaq not being defined. I realized my GA snippet was near the end of the page right before the ending body tag. I moved it up to right after the start of the body tag, as Google now suggests. I still had this problem of an undefined _gaq. Putting
var _gaq = window._gaq || (window._gaq = []);
at the top of my code that had custom events helped solve all my problems, but only if the Google snippet was at the top of the page. This helped me so much, and I didn't have to put it in each click event or in a function anywhere, other than a jQuery ready function.