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']);
}
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');
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With