What is “var _gaq = _gaq || []; ” for?

This line is there to allow multiple GA snippets in the same page. It ensures that the second snippet doesn’t overwrite a _gaq defined by the first.

GA asynchronous tracking works by first defining _gaq as an array. This array acts like a queue, which allows you to push (append) configuration and tracking “commands” (like _trackPageview) onto the end of the queue. Your commands are stored in this array until ga.js fully downloads.

When ga.js is ready, it executes all the commands in the _gaq array and replaces _gaq with an object. This object also has a push method, but instead of queueing up commands, it executes them immediately, because ga.js is available to process them.

This mechanism allows you to make configuration and tracking commands without knowing if the browser has finished downloading ga.js. This is needed because the async snippet downloads ga.js without blocking other code on the page from running. Things would get hairy if that other code (your configuration commands) needed to know the state of ga.js being downloaded.

All of this absolutely does depend on the use of the name _gaq. You shouldn’t try to name it if you want asynchronous tracking to work.

Leave a Comment