Using _gaq asynch in closures

Using

var _gaq = _gaq || []; 

in the script tag, which is necessary to support this in closing to add asynchronous analytics 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 has not yet been determined whether this array will be able to execute the elements that it was clicked on when it is ready. since _gaq var is not publicly available, I assume this will not work. Any workarounds?

+4
source share
3 answers

You can do something like:

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

If done globally, this will do the trick.

+5
source

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

 $( function() { $('.foobar').on('click', function() { var _gaq = window._gaq || (window._gaq = []); _gaq.push(['_trackEvent', 'category', 'action', 'label']); }); }); 
+1
source

I don’t know if this will help other people find the answer, but maybe it will. I had a problem with _gaq that is not defined. I realized that my GA fragment was closer to the end of the page before the end tag. As I said, I moved it right after the start of the tag. I still had a problem with undefined _gaq. Enter

var _gaq = window._gaq || (window._gaq = []);

at the top of my code, in which custom events helped solve all my problems, but only if the Google snippet was at the top of the page. This helped me a lot and I did not have to put it in every click event or in any function other than the jQuery ready function.

0
source

All Articles