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="">
?
As Myforwik said, the event you hook up with
window.onload = ...;
is the same event you hook up with<body onload="...">
. It's thewindow
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 setwindow.onload
independently.To avoid these sorts of issues, use DOM2-style event hookup:
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.