vikmalhotra
vikmalhotra

Reputation: 10071

javascript: <body onload=""> and window.onload

I ran across a weird error today. I had a simple userscript which was adding a window.onload event to all the sites. But one of the sites had a <body onload="func();"> defined. What happened is that window.onload was working as usual but <body onload=""> stopped working for the site after installing userscript.

When I used window.body.onload instead both worked well. I know that window.onload and <body onload=""> are different way of doing the same thing but what is happening in window.body.onload which makes it work well with <body onload="">?

Upvotes: 3

Views: 3923

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

As Myforwik said, the event you hook up with window.onload = ...; is the same event you hook up with <body onload="...">. It's the window load event. Both of those ways of hooking it are in the old DOM0 style, which has been obsolete for some time. If you specify both, the latter one will win, knocking out the former. The same is true if multiple scripts set window.onload independently.

To avoid these sorts of issues, use DOM2-style event hookup:

if (window.addEventListener) {
    // DOM2 standard
    window.addEventListener("load", handler, false);
}
else if (window.attachEvent) {
    // Microsoft's precursor to it, IE8 and earlier
    window.attachEvent("onload", handler);
}
else {
    // Some pre-1999 browser
    window.onload = handler;
}

function handler() {
}

Multiple DOM2 handlers can be attached to the same event, so multiple unrelated scripts can subscribe to it. Also, DOM2 handlers happily co-exist with DOM0 handlers.

So if you update your userscript to use the above, the <body onload="..."> page will be unaffected.

Upvotes: 1

Myforwik
Myforwik

Reputation: 3588

Window.onload and body tag's onload are the same event. So if you set the same event twice by two different methods it will only end up with the one value - one of the functions.

window.body.onload is a seperate event. Just another quirk of the DoM and what broswers do with it.

Upvotes: 2

Related Questions