3

On localhost, I disable my google analytics code by incorporating it into an if statement like so:

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).

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:

var s = window.location + "";

if (s.indexOf('localhost') > 0) {
    ga = function () {};
}

Is there a good best practice for solving this? Thanks!

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
YPCrumble
  • 26,610
  • 23
  • 107
  • 172

1 Answers1

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.

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    Also, if you "setDomainName" to your production URL, GA will still download, but it won't fire into your account: http://stackoverflow.com/questions/4375447/can-you-test-google-analytics-on-a-localhost-address – TomFuertes Dec 25 '13 at 17:51
  • This worked for me. It's an simple solution when you don't want any tracking code in your local dev environment. – Foxinni Oct 21 '14 at 14:01