Move Over onLoad. onDomReady Is Here.
Are you still using the onLoad event to trigger JavaScript actions in your web pages? If so, you really should consider using the much more up-to-date and trendy onDomReady event?
The trouble with onLoad, as I'm sure you're all aware, is that it doesn't exactly trigger when you'd expect it to. It only fires once the whole page has loaded. If it's a page with a lot of images and your connection is slow then it could be a long time coming. If your page relies on JavaScript to work then there could well be a spell of time whereby the user is interacting with the page and it hasn't yet been initialised.
Not only is onLoad not reliable, but it's also a usability nightmare. Something I've talked about before and am reminded of every time I visit Screwfix.com/. The onload event focuses the cursor on the search box. This well-meaning design decision is a usability curse for mousephobic surfers like me. As a regular user of the site I was driven to email them about it (got ignored) and then write myself a Greasemonkey script to blur() the search box once loaded.
More often that not you want the "onload" JavaScript to fire as soon as it's safe to do so — when the HTML document is complete and not necessarily when all the images have loaded. That's why they invented the much more developer-friendly onDomReady event, which triggers once the browser has interpreted the page and rendered it.
There's native support in browsers like Opera and Firefox, but not in IE or Safari. However, people have written custom functions to cater for all browsers. More tomorrow on how to start using it and a demo db etc.
Here's a good little demo of the DomReady Vs OnLoad with the MooTools library : {Link}
Thanks Declan. I was going to mention mootools tomorrow, as there's a bug in its ondomready function. If you use SSL in IE that is. I spent HOURS working that one out!
The best-in-class ready-event abstraction is jQuery's $.ready() method. Also, YUI gives you three different flavors for maximum flexibility: onDOMReady(), onAvailable(), and onContentReady(). I tend to shy away from those in most cases, though.
Ext.onReady is a good one as well... includes a scope parameter so you can override what "this" refers to when the function you're passing is executed.
Jake, I believe that problem was fixed in Mootools v1.1
I also wrote a standalone one called FastInit:
{Link}
Here's a DOMContentLoaded event that I added to Dean Edwards' fabulous addEvent.
{Link}