On localhost, I disable my google analytics code by incorporating it into an if statement like so:
在localhost上,我通过将其合并到if语句中来禁用我的Google Analytics代码,如下所示:
var s = window.location + "";
if (s.indexOf('localhost') < 0) {
//GA universal analytics tracking snippet
}
However, throughout my site there are various event tags using ga('send', 'event', etc...);
- when my GA snippet is disabled on localhost these functions return errors (Uncaught ReferenceError: ga is not defined
).
但是,在我的网站中,有各种使用ga的事件标签('发送','事件'等...); - 当我在本地主机上禁用我的GA片段时,这些函数会返回错误(Uncaught ReferenceError:ga未定义)。
Is there a way to disable these functions without putting them all into their own individual if statements? I was thinking some kind of global statement like this might work, but it doesn't:
有没有办法禁用这些功能而不将它们全部放入各自的if语句中?我在想某种像这样的全局声明可能有用,但它没有:
var s = window.location + "";
if (s.indexOf('localhost') > 0) {
ga = function () {};
}
Is there a good best practice for solving this? Thanks!
解决这个问题有一个很好的最佳实践吗?谢谢!
1 个解决方案
#1
8
It would be simpler to do this :
这样做会更简单:
var ga = ga || (function(){});
If ga
is defined, this does nothing. If it's undefined
, it sets its value to a no-op function, preventing the error.
如果定义了ga,则不执行任何操作。如果未定义,则将其值设置为无操作函数,以防止出错。
But I don't think it's a good idea to disable the script when you develop : it makes one more reason to have an unexpected bug in production. The best practice here would be, in my opinion, to add a filter in Google Analytics. See Exclude internal traffic.
但是我认为在开发时禁用脚本并不是一个好主意:它还有一个原因让生产中出现意外错误。在我看来,这里的最佳做法是在Google Analytics中添加过滤器。请参阅排除内部流量。
#1
8
It would be simpler to do this :
这样做会更简单:
var ga = ga || (function(){});
If ga
is defined, this does nothing. If it's undefined
, it sets its value to a no-op function, preventing the error.
如果定义了ga,则不执行任何操作。如果未定义,则将其值设置为无操作函数,以防止出错。
But I don't think it's a good idea to disable the script when you develop : it makes one more reason to have an unexpected bug in production. The best practice here would be, in my opinion, to add a filter in Google Analytics. See Exclude internal traffic.
但是我认为在开发时禁用脚本并不是一个好主意:它还有一个原因让生产中出现意外错误。在我看来,这里的最佳做法是在Google Analytics中添加过滤器。请参阅排除内部流量。