views:

29

answers:

1

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?

A: 

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
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.
CMS
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.
CD Sanchez
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