What's the name of Google Analytics async design pattern and where is it used? What's the name of Google Analytics async design pattern and where is it used? javascript javascript

What's the name of Google Analytics async design pattern and where is it used?


I've referred to it as "asynchronous function queuing", but its not quite a catchy name, and certainly not the formal name of the design pattern.

What's interesting is that, though I hadn't seen this particular pattern used before, since Google adopted it for Google Analytics, its been adopted widely by different platforms looking to nab the asynchronous juice (Disqus comes to mind.)

This blog post is the most in-depth examination of the async Google Analytics syntax I've read, and includes a fairly detailed explanation of how the one can replicate the pattern:

From the blog post:

var GoogleAnalyticsQueue = function () {    this.push = function () {        for (var i = 0; i < arguments.length; i++) try {            if (typeof arguments[i] === "function") arguments[i]();            else {                // get tracker function from arguments[i][0]                // get tracker function arguments from arguments[i].slice(1)                // call it!  trackers[arguments[i][0]].apply(trackers, arguments[i].slice(1));            }        } catch (e) {}    }    // more code hereā€¦};// get the existing _gaq arrayvar _old_gaq = window._gaq;// create a new _gaq objectwindow._gaq = new GoogleAnalyticsQueue();// execute all of the queued up events - apply() turns the array entries into individual argumentswindow._gaq.push.apply(window._gaq, _old_gaq);

It also notes that, even though not many browsers support the async attribute, the method of injection used makes the script load asynchronously in most browsers, and includes a helpful chart:

enter image description here


All it's doing is pushing data into a global array

var _qaq = _qaq || [];_qaq.push(stuff);

It basically allows you to buffer up data to deal with before the library has loaded.

The main reason this pattern isn't used much is that other libraries generally need the resources to load before they can do anything. It wouldn't make any sense to start buffering jQuery commands.

It's not a pattern it's simply storing data in global scope and saying it's some-one elses job to process this, I don't care when you process it.

However it is a clever way to deal with the fact you don't know when something is loaded or ready, the common alternative is a DOMReady block.


A good writeup of javascript loading stratgies is available herehttp://friendlybit.com/js/lazy-loading-asyncronous-javascript/

And as far as I recall, ga.js async syntax has been inspired by Steve Souders. You can look at ControlJS , one of his projects