I have examined Dean Edward’s onload post and have a question: what’s wrong with this onload attaching method? Where and why can it fail? And when is it safe to use this simpler function?
function addLoadEvent(func){
var oldonload = window.onload;
if(typeof window.onload != 'function'){
window.onload = func;
}else{
window.onload = function(){
oldonload();
func();
}
}
}
The point of Dean’s post isn’t about how to hook the
window.loadevent, but rather how to hook a useful event prior towindow.load.window.loadhappens very, very late in the page load cycle (after all resources, including all images, are fully loaded). If your page has any significant resources and you wait untilwindow.loadto hook up your event handlers, your users are likely to start doing things before your handlers are hooked up.Note that Dean’s article was written in 2006. The modern practice is to simply put your script just prior to the closing
</body>tag. As long as your script is after any elements it refers to, the elements will be accessible to you. That way, you hook things up very early on indeed.Example (live copy):
HTML:
JavaScript (just before
</body>end tag):If you can’t do that (put the script at the end of the
bodyelement) for some reason, then tricks like Dean’s start being useful, but I’d strongly recommend against DIY “DOM loaded” handling; instead, use a good, well-maintained library like jQuery, Prototype, YUI, or any of several others and use their “ready” event. By leveraging the ongoing work put into those libraries, you can instead focus on what you’re trying to do with your own page/app.References:
[Re
window.loadspecifically: You don’t have to resort to your trick, just useaddEventListener(if the browser supports it, all do except older IE versions) orattachEvent(older IE). SeehookLoadin the example above. Those allow multiple handlers for an event.]