A simple Javascript Queue for Asynchronous Loading

This post was migrated over from Muziboo DevBlog. YSlow is a popular tool for measuring and tweaking site performance. The tool recommends that Javascript be put at the bottom of the page (since javascript blocks the page until its loaded). However one of the challenges of doing this is that you cannot call any javascript function (that you have defined in your js files) before the files are loaded. This can be a serious limitation if you are doing a dynamic website where the header and footer (which is where the script tags are inserted) is static and all the dynamic content is in the middle of the page. If you have used any Ruby on Rails or similar framework, you know what I mean. Basically, its hard to put different code in the footer for different pages.

Lets take an example from Muziboo. I have a function in javascript to initialize the flash player Muziboo.Player.embedSingle(). If my script tags (for including the js) are in the header, I can make this call anywhere on the page and it will work. However if the javascript files are loaded last, this call has to be made after loading the javascript.

However you can overcome this limitation by using a javascript queue that holds the function calls till the external javascript files are loaded. Once the javascript is loaded, it can look at the queue and process the messages. So something like this would work

This idea is not new and is used by Google Analytics' async tracking code. Lets see how to implement such a queue in javascript (using the prototype.js javascript library)

The queue is nothing but a simple javascript array. The process message simply pops out each message, executes it and then changes the push method on _muzq object to execute the message instead of storing it (since now the js is loaded and there is no need to wait). I am still trying to find out a better way than to use eval but this implementation works.

blog comments powered by Disqus
Hana Mohan
Hana Mohan