To the former: no, that is entirely redundant (quite literally: you can refer to it as window.window.window.window.window.onload if you want). We're in global scope here, so there is nothing that could possibly be shadowing onload in a higher scope: we can only be referring to the global onload (as you probably know, all globals are properties of the global [window] object, and vice versa). Certainly there's no harm in using addEventListener/attachEvent, and I've a chunk of code for that, too:
Code:
var Event = (function() {
function addEventW3C(el, ev, f) {
return el.addEventListener(ev, f, false);
}
function removeEventW3C(el, ev, f) {
el.removeEventListener(ev, f, false);
}
function addEventIE(el, ev, f) {
((el._evts = el._evts || [])[el._evts.length]
= function(e) { return f.call(el, e); })._w = f;
return el.attachEvent("on" + ev,
el._evts[el._evts.length - 1]);
}
function removeEventIE(el, ev, f) {
for (var evts = el._evts || [], i = evts.length; i--; )
if (evts[i]._w === f)
el.detachEvent("on" + ev, evts.splice(i, 1)[0]);
}
function addEventLegacyHandler(e) {
var evts = this._evts[e.type];
for (var i = 0; i < evts.length; ++i)
if (!evts[i].call(this, e || event))
return false;
}
function addEventLegacy(el, ev, f) {
if (!el._evts)
el._evts = {};
if (!el._evts[ev])
el._evts[ev] = [];
el._evts[ev].push(f);
return true;
}
function removeEventLegacy(el, ev, f) {
for (var evts = el._evts[ev] || [], i = evts.length; i--; )
if (evts[i] === f)
evts.splice(i, 1);
}
return window.addEventListener
? {add: addEventW3C, remove: removeEventW3C}
: window.attachEvent
? {add: addEventIE, remove: removeEventIE}
: {add: addEventLegacy, remove: removeEventLegacy};
})();
Code:
Event.add(window, "load", Background.restoreImage);
I usually don't go the whole nine yards with this one, since, as you say, it's really preferable to insert a <script> element just inside the <body>.
As it happens, we can actually remove the necessity for this line altogether, at least in standards-compliant browsers, by simply changing:
Code:
document.body.style.backgroundImage = 'url(' + path + ')';
to:
Code:
document.documentElement.style.backgroundImage = 'url(' + path + ')';
However, I'm leery of doing so since it seems like the sort of thing IE might not support under some bizarre combination of circumstances. Perhaps you could give this a test?
Bookmarks