特别说明:当页面出现多个window.onload时,就会出现意想不到的事情,比如后面的window.onload会覆盖前面的window.onload。那怎么解决有需要多个函数在window.onload下执行呢!?实现代码如下:
->window_onload.js
// 注意:会被嵌入页面的Onload覆盖;
function externalFn() {
console.log("->The Onload in External JS!");
}
window.onload = function() {
externalFn();
}
->window_onload.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>window_onload加载问题</title>
<script type="text/javascript" src="window_onload.js"></script>
<script type="text/javascript">
function insideFn() {
console.log("->The Onload inside page!");
}
// 注意:会覆盖外部JS中的Onload
/*window.onload = function() {
insideFn();
}*/
// 改善
(function autoRun() {
var oldFn = window.onload;
if(typeof oldFn != "function") {
window.onload = insideFn;
}else {
window.onload = function() {
oldFn();
insideFn();
}
}
})();
</script>
</head>
<body>
</body>
</html>
这样就能保证:不论你在加入代码之前,有没有window.onload,都能保证页面能正常运行,而不必担心新加的window.onload会覆盖之前有可能存在的window.onload!