views:

171

answers:

2

I'm switching over our site to use Asynchronous Google Analytics, and I'm curious about it's method of pushing events to the _gaq array. Near as I can tell, events are placed into a waiting pattern in _gaq while the ga.js script is being asynchronously downloaded. Do they fire once the script is downloaded, and how are post-document load events tracked?

One example is a user clicking a link 10 seconds after page load - according to documentation the event should be placed into the _gaq. How does the analytics script detect this?

A: 

It's always difficult to un-obfuscate the google analytics code, but if I were to solve this problem, upon loading the script, I would redefine the push function on the array after processing everything in the backlog queue (_gaq). This way, the redefined push function would simply act as a proxy to the actual function calls on the pageTracker object.

Here's a simple example of redefining the push method on an array object:

var foo = [];
foo.push("one");                      // pushes "one" onto the array
foo.push("two");                      // pushes "two" onto the array
foo.push = function(a) { alert(a) };  // redefines `push`
foo.push("three");                    // alerts "three"
alert(foo);                           // alerts "one,two"
Ryan McGeary
+2  A: 

The general part is best described by the Google Analytics Async doc.

To push an API call onto the queue, you must convert it from the traditional JavaScript syntax into a command array. Command arrays are simply JavaScript arrays that conform to a certain format. The first element in a command array is the name of the tracker object method you want to call. It must be a string. The rest of the elements are the arguments you want to pass to the tracker object method. These can be any JavaScript value.

I'll try to explain the juicy details: _gaq is just a plain JavaScript Array, and all arrays have the push method to add an entry to the end of the array. So before the Analytics script is loaded, all commands will be pushed to the array. At the end of the Analytics script, it replaces the _gaq.push method with a custom method and executes all entries in the _gaq array. The new _gaq.push method will run the tracking method instantly. So when you run the push method 10 seconds after page load, the command should be executed.

gregers
I did some logging on the _gaq, and before the script is loaded it's just a simple array. Once the script is pulled down, the _gaq is converted to a traditional analytics object, which verifies what you're saying.
Mike Robinson