user1026361 user1026361 - 1 month ago 23
HTML Question

How to tell if Google Analytics is loaded

I make a lot of javascript widgets. As part of these widgets, we often use Google Analytics to track actions within the widget. Simplified, what I do is:

var setupGA = function(){ window._gaq.push(['_setAccount', 'UA-###']); };
if(window._gaq){
setupGA();
} else {
this.loadScript(GOOGLE_ANALYTICS_PATH, function(){
var waitga = setInterval(function(){
if(window._gaq){
clearInterval(waitga);
setupGA();
}
}, 500);
});
}


Where GOOGLE_ANALYTICS_PATH is my local path to the file and loadScript is a custom method to load the script and execute a callback.

With Google updating their analytics library (now analytics.js), old methods of ensuring that the analytics library has been loaded no longer work. The example code for google analytics helpfully provides a global ga object, but this object can have a custom name. With the old queue to check, I'm wondering how best I can check for the existance of either analytic.js or ga.js versions of google analytics (I Can skip the very old Urchin Tracking types).

It must be something like:

var setupGA = function(){ window._gaq.push(['_setAccount', 'UA-###']); };
if(window._gaq && !window.**ga**){
setupGA();
} else {
this.loadScript(GOOGLE_ANALYTICS_PATH, function(){
var waitga = setInterval(function(){
//_gaq will always be loaded for now
if(window._gaq){
clearInterval(waitga);
setupGA();
}
}, 500);
});
}


Where the ga is whatever global element I can check. I suppose thats what I'm looking for

Answer

Answered my own question with a little more exploration.

With the new Universal Analytics platform, it seems that a window level variable is created. That variable is called GoogleAnalyticsObject. This object will give you the variable name created to house the Universal Analytics Object

EX:  Using (window,document,'script','//www.google-analytics.com/analytics.js','ga'); will return "ga"
EX:  Using (window,document,'script','//www.google-analytics.com/analytics.js','notGA');  will return "notGA"

You can then use this variable to pull the Analytics object:

window[window.GoogleAnalyticsObject]