Reputation: 114126
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!");
}
Upvotes: 40
Views: 132794
Reputation: 25
Why not using jQuery?
$(document).ready(function(){}))
As far as I know, this is the perfect solution.
Upvotes: -4
Reputation: 6411
Cross browser window.load event
function load(){}
window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )
Upvotes: 15
Reputation: 1167
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.
Upvotes: 9
Reputation: 2938
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
.
Upvotes: 2
Reputation: 106412
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.
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
Upvotes: 22
Reputation: 108050
Why not use window
's own onload
event ?
window.onload = function () {
alert("LOADED!");
}
If I'm not mistaken, that is compatible across all browsers.
Upvotes: 25