How do I attach a body onload event with JS in a cross browser way? As simple as this?
document.body.onload = function(){
alert("LOADED!");
}
How do I attach a body onload event with JS in a cross browser way? As simple as this?
document.body.onload = function(){
alert("LOADED!");
}
Why not using jQuery?
As far as I know, this is the perfect solution.
This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...
window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.
Why not use
window
's ownonload
event ?If I'm not mistaken, that is compatible across all browsers.
There are several different methods you have to use for different browsers. Libraries like jQuery give you a cross-browser interface that handles it all for you, though.
Cross browser window.load event
document.body.onload
is a cross-browser, but a legacy mechanism that only allows a single callback (you cannot assign multiple functions to it).The closest "standard" alternative,
addEventListener
is not supported by Internet Explorer (it usesattachEvent
), so you will likely want to use a library (jQuery, MooTools, prototype.js, etc.) to abstract the cross-browser ugliness for you.