Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  161] [ 7]  / answers: 1 / hits: 17808  / 12 Years ago, fri, november 16, 2012, 12:00:00

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

More From » jquery

 Answers
67

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.


[#81960] Wednesday, November 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
noe

Total Points: 149
Total Questions: 91
Total Answers: 91

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
;