你的代码没问题。问题是设置事件处理程序 http://www.quirksmode.org/dom/w3c_events.html in the DOM 0 方式不能确保他们不会替换为其他代码.
您可以尝试新的 W3C 标准 addEventListener https://developer.mozilla.org/en/DOM/element.addEventListener和IE版本attachEvent http://msdn.microsoft.com/en-us/library/ms536343(VS.85).aspx,因为您附加的处理程序无法被第 3 方代码替换。
// window.onload W3C cross-browser with a fallback
function addLoadEvent(func) {
if (window.addEventListener)
window.addEventListener("load", func, false);
else if (window.attachEvent)
window.attachEvent("onload", func);
else { // fallback
var old = window.onload;
window.onload = function() {
if (old) old();
func();
};
}
}
请注意,IE 将以相反的顺序执行该函数,而不是按照您添加它们的顺序(如果这是一个问题)。
最后,我不知道你想什么时候运行你的代码,但如果你不想等待图像加载您可以更早地执行您的功能然后是window.onload。
迪恩·爱德华兹 http://dean.edwards.name has a 不错的剧本 http://dean.edwards.name/weblog/2006/06/again/这会让你这样做。
有了这个,您可以附加您的功能earlier event: 文档准备好(DOM内容已加载)
// document.ready
function addLoadEvent(func) {
if (typeof func == "function") {
addLoadEvent.queue.push(func);
}
}
addLoadEvent.queue = [];
//////////////////////////////////////////////////////////////////////////////
// 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: execute the queue
var que = addLoadEvent.queue;
var len = que.length;
for(var i = 0; i < len; i++) {
if (typeof que[i] == "function") {
que[i]();
}
}
};
/* 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;
注意:两种方法的用法与您的版本相同。