checking if the Google Analytics _gaq object is loaded and available

crmpicco picture crmpicco · Nov 16, 2012 · Viewed 17.3k times · Source

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']);                                    
}

Answer

Mike picture Mike · Jul 4, 2013

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');