4

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?

Yahel
  • 37,023
  • 22
  • 103
  • 153
claya
  • 1,920
  • 1
  • 18
  • 32

3 Answers3

5

You could do something like:

(function (window) {
    var g = window._gaq || (window._gaq = []);
    g.push(['_setAccount', 'UA-XXXXX-X']);
    g.push(['_trackPageview']);
})(this);

If executed in the global scope this would do the trick.

Anthony Mills
  • 8,676
  • 4
  • 32
  • 51
  • Inside the function `window` will be `undefined`, that will cause a `TypeError` exception when the `window._gaq` property is accessed. The first argument of `call` is used as the `this` value inside the invoked function, the `window` argument is not being supplied. – Christian C. Salvadó Sep 01 '10 at 23:41
  • You're better off leaving the function with no arguments since the `window` variable is already bound to what you want, albeit higher up the scope chain. – Cristian Sanchez Sep 02 '10 at 01:42
  • CMS: You're totally right, and I know what `call` does; just a mental blurp. Daniel: mainly I'm passing it in so you can use this with non-browser-hosted environments. Of course, I don't know why you'd be trying to track pageviews in a non-browser-hosted environment, but it's a good habit to not assume that the global object is `window`. – Anthony Mills Sep 02 '10 at 14:21
1

This works (using jQuery's notation for document.ready):

$( function() {
    $('.foobar').on('click', function() {
        var _gaq = window._gaq || (window._gaq = []);
        _gaq.push(['_trackEvent', 'category', 'action', 'label']);
    });
});
blueyed
  • 27,102
  • 4
  • 75
  • 71
0

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.

amurrell
  • 2,383
  • 22
  • 26