Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if the Google Analytics _gaq object is loaded and available

I have some Google Analytics Tracking Code (GATC) on my site which triggers calls to the _gaq.push method in Google's code.

In the scenario that GA is not available, or _gaq has not loaded, I want to ensure that I do not have any JavaScript errors on the page. By checking that _gaq is not identical to 'undefined' - will this suffice to check if it's available and is this x-browser? I've had a look at Google's documentation, but it doesn't mention anything about this.

I'm aware of checking if the object is null, but i'm not sure if this is necessary.

if (typeof(_gaq) !== 'undefined') {
   _gaq.push(['_trackEvent', 'Downloaded Video', 'Yes']); 
   _gaq.push(['rollup._trackEvent', 'Downloaded Video', 'Yes']);                                    
}
like image 881
crmpicco Avatar asked Nov 16 '12 10:11

crmpicco


3 Answers

If you're using Universal Analytics (analytics.js) then switch this:

_gaq.push(['_trackEvent', 'Downloaded Video', 'Yes']); 

to this:

ga('send', 'event', 'Downloaded Video', 'Yes');
like image 103
Mike Avatar answered Sep 20 '22 15:09

Mike


In the recommended javascript code you get from analytics, it includes the following row:

var _gaq = _gaq || [];

So, the array should always be available if you keep this line in your code. If you are adding the analytics code later, just add the line above before your main scripts and it will work.

Note that this snippet is harmless even if you defined _gaq before, since it only defines it as a new Array it if it is previously undefined.

This is a great way to use asynchronous scripts, the array is defined first locally, and you can push commands to this array whenever you need. When the analytics script is loaded, it can use those commands when it wants. So no need for checking if the array is undefined or anything like that.

like image 34
David Hellsing Avatar answered Sep 21 '22 15:09

David Hellsing


When ga.js is loaded, it defines a window._gat (Mind the T instead of Q) global object, you just need to test if it is defined or not (but beware it is loaded asynchronously, then you may delay your test).

like image 27
Open SEO Avatar answered Sep 21 '22 15:09

Open SEO