This is not an instructional post on how to use Google Analytics, but a quick teardown to highlight some clever things the script does to optimize page load speed and work around network latency issues.
How does the Google Analytics tracking snippet work? The code they tell you to paste into your site is an opaque mess:
Lets clean up the function contents a little bit.
Things to point out:
eimmediate function is used as a minifier/scope protector. It neatly avoids polluting the global scope and removes the necessity of referring to
mare passed in as declared parameters so the script can save 4 bytes on a
- It dynamically adds a script tag to asynchronously load the full tracking payload, allowing the browser to continue rendering and downloading other assets.
- The parameter names are not semantic and are chosen to spell out ISOGRAM, which must be an inside joke to Google’s developers.
The async load presents a problem: what happens if the
analytics.js file is slow to load? We don’t want any tracking events to be lost, especially since the first calls to the analytics code set up important parameters like the websites owner’s identification.
They neatly solve this by declaring the tracking function
ga immediately. It looks to see if there is a
window.ga.q object (think queue), and if not, it sets it to a new
ga function can then
push events into the queue at will using the usual
analytics.js file will load and empty the queue, replacing the
window.ga.q array with its own custom object. That object implements a
push function as well, which sends out the tracking beacon on demand.