Monday, September 13, 2010

Asynchronous Javascript

There are many javascript frameworks and tools that can help the besieged web-developer in their quest to slay the dragon. I personally use jQuery for even the most menial of tasks thanks to its beautiful monadic design, however, even the miniscule 72k of minified jQuery source is still going to slow down page-load on slow connections. Combine this with CSS resources, other javascript files, and what-have-you, and your page will stall on grandma's computer.

The very simple solution I have implemented on sordina.net is to create a small asynchronous function that triggers a download of resources using setTimeout:


/*
 * Simple async callback function for loading external scripts without
 * slowing down the page.
 */
function async(element,options,callback){
function f(){
var e = document.createElement(element)
for(var i in options) { e[i] = options[i] }
if(callback) {
if(element == "link") {
if(options['type'] == 'text/css') onloadCSS(element, callback)
} else {
e.onload = callback
}
}
document.getElementsByTagName('head')[0].appendChild(e)
}
setTimeout(f,0); // This makes the function asyncronous
}

I began thinking about this issue as I was sitting on a wireless connection that had multi-second pings. Requests to jQuery, Google Font Directory, and other external resources were slowing down the loading of my page even though I was developing it from a web-server on my laptop.

Now that I am using the "async" function the page loads very quickly in this scenario, with dynamic and stylistic functionality being loaded into the page as resources become available. So long as you are designing your pages to use graceful degradation, this shouldn't be a major issue.

Until next time, let me know if I've just blogged any hideous bugs!

No comments:

Post a Comment