Asynchronous syntax18 Jul 2015 · 4 min read · comments
How we usually solve it?
The most common solution for this problem is checking if the object exists every several milliseconds.
It is a hack though.
How others do it?
Google, Optimizely, Qualaroo and many others, I believe, are all using an interesting technique of caching API calls. Lets see how to track an event in Optimizely:
We don’t need the Optimizely object at all! We pass instructions that will be executed once the Optimizely script is loaded.
Qualaroo does the same. E.g., here’s how to force Qualaroo to start the surveys in minimized state:
Google Analytics also caches the calls inside the
ga function until the main
script is loaded. You can see it from the implementation of
Even though this hack is very popular, I could never find an article
about it. I didn’t even know how this technique is called. Only a few days ago
I’ve accidentally came across this article: Tracking Basics (Asynchronous Syntax).
Asynchronous Syntax! So that’s how it is called. The article is dedicated to
the usage of
ga in an asynchronous way but contains many useful explanations
about the Asynchronous Syntax as well. The next section is from that page.
How the Asynchronous Syntax Works
This section is from Tracking Basics (Asynchronous Syntax)
_gaq object is what makes the asynchronous syntax possible. It acts as a
queue, which is a first-in, first-out data structure that collects API calls
until ga.js is ready to execute them. To add something to the queue, use the
The following code calls
_trackPageview() using the traditional syntax:
The equivalent code in the asynchronous syntax requires two calls to
Lets see how it works on a simple
Logger object that is just a wrapper over the
All that we have to do in order to make it usable in an asynchronous way is to
pass it to the
applyq method after creation, along with the array that contains
the cached commands.
_loggerq will always print the messages. Immediately or after the