Peter Michaux has written a detailed post on the window.onload problem:
The goal of unobtrusive JavaScript programming it to separate the JavaScript behavior from from the HTML content and is analogous to the goal of unobtrusive CSS design to separate the CSS presentation from the HTML content. Separation of presentation and content has been possible for years but there is one wrinkle standing in the way of completely separating the behavior. This article is about previously suggested techniques to enable this separation, their problems and a new option that combines the strengths of the current techniques with an extra bonus into a new robust solution.
Peter goes into detail on the various tricks and hacks that differ between browsers in many cases.
He discusses:
- Just putting a script tag where you need it
- DOMContentLoaded for some browsers
- script tag with an onreadystatechange
- document.readyState
- DOM Polling (e.g. YUI event library)
Summary
Event handler attributes in the HTML are the most robust but do not allow separation of concerns.
The bottom script technique works cross browser based on de facto standard browser behavior but has a compromise in separation of concerns. Must remember to put the JavaScript element at the bottom of each page.
Dean Edwards script allows for complete separation but is brittle when looking towards the future. Old and exotic browsers will not enliven a page until window.onload.
DOM polling is cross browser, robust and allows for complete separation of concerns. In extremely rare cases a dummy element can help the code know that content is available.
The Fork JavaScript library svn trunk now implements DOM polling with DOMContentloaded and window.onload fallbacks as well as the ancestor walk as discussed. These features will be part of Fork release 0.2.0.