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!");
}
This question is related to
javascript
html
events
onload
Cross browser window.load event
function load(){}
window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )
Why not using jQuery?
$(document).ready(function(){}))
As far as I know, this is the perfect solution.
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.
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 uses attachEvent
), so you will likely want to use a library (jQuery, MooTools, prototype.js, etc.) to abstract the cross-browser ugliness for you.
jcalfee314's idea worked for me - I had a window.onload = onLoad
which meant that the functions in <body onload="...">
were not being called (which I don't have control over).
This fixed it:
oldOnLoad = window.onload
window.onload = onLoad;
function onLoad()
{
oldOnLoad();
...
}
Edit: Firefox didn't like oldOnLoad = document.body.onload;
, so replaced with oldOnLoad = window.onload
.
Why not use window
's own onload
event ?
window.onload = function () {
alert("LOADED!");
}
If I'm not mistaken, that is compatible across all browsers.
Source: Stackoverflow.com