对于初学者也许这个问题很简单,但实际上还是值得一说的。
一般来说我们可以用<body onload="">或者window.onload(他们两会被对方覆盖),为了防止覆盖,我们可以写以下一个函数:
/* window 'load' attachment */
function addLoadEvent(func) {
var oldonload = window.onload;
//if there is on one set the onload function, there we set it
if (typeof window.onload != 'function') {
window.onload = func;
}
/*if there is already a onload function set by <body onload=""> or other ways,
we call other load event handler frist
and then we call the new event handler
*/
else {
window.onload = function() {
oldonload();
func();
}
}
}
问题是onload要等到DOM中所有元素下载完毕才激发(例如图片),如果你只需要HTML下载完毕可以参考这个:
http://www.thefutureoftheweb.com/blog/adddomloadevent
这个函数分别用了以下几个特殊属性:
- DOMContentLoaded
- onreadystatechange
- document.readyState
addDOMLoadEvent = (function(){
// create event function stack
var load_events = [],
load_timer,
script,
done,
exec,
old_onload,
init = function () {
done = true;
// kill the timer
clearInterval(load_timer);
// execute each function in the stack in the order they were added
while (exec = load_events.shift())
exec();
if (script) script.onreadystatechange = '';
};
return function (func) {
// if the init function was already ran, just run this function now and stop
if (done) return func();
if (!load_events[0]) {
// 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=//0><\/scr"+"ipt>");
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
load_timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState))
init(); // call the onload handler
}, 10);
}
// for other browsers set the window.onload, but also execute the old window.onload
old_onload = window.onload;
window.onload = function() {
init();
if (old_onload) old_onload();
};
}
load_events.push(func);
}
})();