javascript为网页添加onReady重载方法
代码主要转自网络,出处不明,对其作了一小点修改。
代码
(function() {
var addEvent = function(obj, type, fn) {
if (obj.addEventListener)
obj.addEventListener(type, fn, false);
else if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj.attachEvent("on" + type, function() {
obj["e" + type + fn]();
});
}
};
var onReady = function(loadEvent, waitForImages) {
if (waitForImages) {
return addEvent(window, 'load', loadEvent);
}
var init = function() {
if (arguments.callee.done) return;
arguments.callee.done = true;
loadEvent.apply(document, arguments);
};
if (! +"\v1") {
if (window.self == window.top) {
(function() {
try {
document.documentElement.doScroll("left");
} catch (e) {
setTimeout(arguments.callee, 0);
return;
}
init();
})();
} else {
document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", arguments.callee);
init();
}
});
}
} else {
document.addEventListener("DOMContentLoaded", function() {
document.removeEventListener("DOMContentLoaded", arguments.callee, false);
init();
}, false);
}
return true;
}
if (!window.onReady) {
window["onReady"] = onReady;
}
})();
var addEvent = function(obj, type, fn) {
if (obj.addEventListener)
obj.addEventListener(type, fn, false);
else if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj.attachEvent("on" + type, function() {
obj["e" + type + fn]();
});
}
};
var onReady = function(loadEvent, waitForImages) {
if (waitForImages) {
return addEvent(window, 'load', loadEvent);
}
var init = function() {
if (arguments.callee.done) return;
arguments.callee.done = true;
loadEvent.apply(document, arguments);
};
if (! +"\v1") {
if (window.self == window.top) {
(function() {
try {
document.documentElement.doScroll("left");
} catch (e) {
setTimeout(arguments.callee, 0);
return;
}
init();
})();
} else {
document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", arguments.callee);
init();
}
});
}
} else {
document.addEventListener("DOMContentLoaded", function() {
document.removeEventListener("DOMContentLoaded", arguments.callee, false);
init();
}, false);
}
return true;
}
if (!window.onReady) {
window["onReady"] = onReady;
}
})();
使用时,将本JS代码首先加载。
在同一个页面中可以有多个onReady调用:
代码
<html>
<head>
引及本JS
<script /*..1..*/>
onReady(function(){/*do something*/});
</script>
</head>
<body>
……
<script /*..2..*/>
onReady(function(){/*do something*/});
</script>
</body>
</html>
<head>
引及本JS
<script /*..1..*/>
onReady(function(){/*do something*/});
</script>
</head>
<body>
……
<script /*..2..*/>
onReady(function(){/*do something*/});
</script>
</body>
</html>