The Google Analytics async code uses a very clear design pattern to execute javascript code.
The code is library dependent, and it does not know if the library is loaded or not. If the library has not loaded yet, it simply queues all the commands in an Array object. When the library loads, it simply creates the _gaq object and executes all the commands in the sequence in which it was included. Then it overwrites the push function, so future commands are executed immediately.
The idea is to get teams to work very fast when they are queued. The code is really evaluated only after loading the library.
They also load the library with async=true . This has virtually no effect on the actual page load time.
The commands look the same as the synchronization versions, but the first line is the name of the function, and the following parameters are the parameters of the function. You can also embed functions in this array, and the functions will be executed in sequence, as well as with zero context. Therefore, if you need to do something synchronously with the library, you can press a function to do it inside _gaq.
I think this is a very smart solution, but I have never seen it before. Does anyone know the name of this design pattern, or where is it used in addition to the Google Analytics tracking code?
javascript design-patterns google-analytics
Eduardo Aug 05 '11 at 23:50 2011-08-05 23:50
source share