views:

120

answers:

3

I'm working on a project here that will store some info in Google Analytics custom variables. The script I'm building out needs to detect if GA has loaded yet before I can push data to it. The project is being designed to work across any kind of site that uses GA. The problem is reliably detecting if GA has finished loading or not and is available.

A couple of variabilities here:

1) There's multiple methods of loading GA. Older scripts from the Urchin days up to the latest asynchronous scripts. Some of these are inline, some are asynchronous. Also, some sites do custom methods of loading GA, like at my job. We use YUI getScript to load it.

2) Variable-variable names. In some scripts, the variable name assigned to GA is "pageTracker". In others, its "_gaq". Then there's the infinity of custom variable names that sites could be using for their implementation of GA.

So does anyone have any thoughts on what might be a reliable way to check if Google Analytics is being used on the page, and if it's been loaded?

+3  A: 
function checkIfAnalyticsLoaded() {
  if (window.gat_ && window.gat_.getTracker_) {
    // Do tracking with new-style analytics
  } else if (window.urchinTracker) {
    // Do tracking with old-style analytics
  } else {
    // Probably want to cap the total number of times you call this.
    setTimeout(500, checkIfAnalyticsLoaded();
  }
}
Annie
"Then there's the infinity of custom variable names that sites could be using for their implementation of GA." Checking for individual variable names isn't going to work universally.
Geuis
Only if you need to actually interact with the custom variable names that sites have made up. Just checking for the old and new versions of analytics will tell you if it is "being used on the page and loaded".
Annie
Justin Johnson
Thanks, code updated.
Annie
A: 

you may also look into the new Asynchronous Tracking and then you wont need to check you can just do whatever and it will send the data as soon as it loads...

Carter Cole
A: 

I'm too lowly to respond to Annie's answer which works but has syntax errors. Analytics names have underscore first and the setTimeout() syntax was backwards (and incomplete). It should be this:

function checkIfAnalyticsLoaded() {
  if (window._gat && window._gat._getTracker) {
    // Do tracking with new-style analytics
  } else if (window.urchinTracker) {
    // Do tracking with old-style analytics
  } else {
    // Probably want to cap the total number of times you call this.
    setTimeout('checkIfAnalyticsLoaded()', 500);
  }
}
soutarm