这是一个跨浏览器的 window.onload 脚本,我想在页面加载时添加一条消息 ( <div id="message">Loading, please wait</div>
),并且当页面加载完成时它必须消失。我怎样才能做到这一点?请帮忙。
function init() {
if (arguments.callee.done) return;
arguments.callee.done = true;
};
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=\"__ie_onload\" defer=\"defer\" src=\"javascript:void(0)\"><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init();
}
};
/*@end @*/
if (/WebKit/i.test(navigator.userAgent)) {
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(_timer);
init();
}
}, 10);
}
window.onload = init;
最佳答案
最简单的方法是在 DOM 中添加一个在加载事件时隐藏的 div:
<html>
<body>
<div id="loading">The page is loading, please wait</div>
[...]
<script>
window.onload = function () {
document.getElementById('loading').style.display = "none";
}
</script>
</body>
</html>
为了确保它始终有效,即使用户禁用了 JavaScript:
<html>
<body>
<script>
document.write('<div id="loading">The page is loading, please wait</div>');
</script>
[...]
<script>
window.onload = function () {
document.getElementById('loading').style.display = "none";
}
</script>
</body>
</html>
关于javascript - 加载时的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1032107/