Reputation: 57998
I am trying to understand how this would ever work:
_gaq = _gaq || [];
_gaq.push(['trackEvent', 'something', 'bleee']);
Ok, so i get it, i am pushing data into some magic array. But how does google's script know that i have done this? It must either be polling this array (unlikely), or it does something with it when user navigates away from the page.
I have found that making requests when navigating away from the page usually results in the connection being closed before the request completes.
Can someone explain to me how this magic works?
Upvotes: 4
Views: 858
Reputation: 76003
Google has created their own object with a custom .push()
method. So when you push something onto the "array" it activates more code (a function) that creates a tracking pixel and wallah.
Google did this so that if you attempt to use the push method of the _gaq
array before the G.A. snippet has been evaluated, you're just creating a queue of commands to send to Google (in a standard array). If the G.A. snippet has already been evaluated then you're actually running a custom function that Google created to replace the .push
method.
This function is named push so that an array can be used in the place of _gaq before Analytics has completely loaded. While Analytics is loading, commands will be pushed/queued onto the array. When Analytics finishes loading, it replaces the array with the _gaq object and executes all the queued commands. Subsequent calls to _gaq.push resolve to this function, which executes commands as they are pushed.
*Source: https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApi_gaq#_gaq.push*
Upvotes: 5
Reputation: 30217
The array _gaq is read by google analytics js library when the library is loaded. _gaq is only a list of methods (with their parameters) to be called when the library is successfully loaded. Piwik, another Web analytics system, use the same approach.
Upvotes: 0