Speeding Up Unobtrusive JavaScript By Beating window.onload

Posted on Tuesday, November 6th, 2007

I am looking to rework a couple of my scripts here at Unintentionally Blank as in the time since writing them I have learned a lot about accessible, unobtrusive JavaScript. My old scripts no longer cut it and it is time to improve them. Before I start, I wanted to beat window.onload, the event that tells your JavaScript functions that everything has loaded and you can use the DOM now. I had heard of solutions to this before, but now I was to start developing these scripts again I wanted to find the best solution.

Why Take On window.onload

Unobtrusive JavaScript relies on externalising all your JavaScript code and calling it in via <script> declarations in your HTML document’s <head>. With this method, adding functions to elements in the document needs to be done by attaching event handlers which classically was done with window.onload. However, window.onload only fires once the document and any elements in the document have loaded. So, if you have large images or lots of them the window.onload event will not fire until everything has loaded. This has the potential of leaving any elements you want to give events to go without them, potentially allowing users to click on these elements and not receive the enhanced behaviour that your JavaScript was just waiting to provide.

Beating window.onload by adding event handlers when the DOM, but not necessarily the content and images, has loaded reduces this time and quickens the page’s response.

The Solutions

Looking around the internet threw up a number of increasingly complicated solutions. Dean Edwards seemed to come up with the original solution which was steadily improved until a final version as released (and subsequently used in the JQuery library, I believe). Peter Michaux followed up with some increasingly complicated stuff to remove the time between the page becoming visible and the events being attached, but the Dean Edwards method seems to work for most applications on a small scale.

Following in the footsteps of Dean and packaging the function up into a standalone solution was Jesse Skinner with his addDOMLoadEvent. Not only did this implement the solution nicely, with all the updates that have occurred since the original solving, Jesse also compressed the function as best as possible. The current version stands at only 671 bytes in size and works in Internet Explorer, Firefox, Opera 9 and Safari, plus degrades nicely to use window.onload for any browsers that don’t support the technique.

Coming up soon then, will be the return of my scripts, faster, more accessible and generally better than ever before thanks to this and other techniques I have picked up over the last year. It will be like an early Christmas present, I can’t wait!

If you enjoyed this post, why not subscribe to Unintentionally Blank

Comments

Leave a Comment