window.onload和window.document.readystate的探究
在编写前端页面的时候,我们时常需要对页面加载的状态进行判断,以便进行相应的操作。
比如在移动端,时常需要在页面完全加载完成之前,先显示一个loading的图标,等待页面完成加载完成后,才显示出真正要展现的页面元素。见代码1:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
function isLoaded(t)
{
if (window.document.readyState == "complete")
{
$("#loading").hide();
$("#wrapper").show();
if (t) {
window.clearInterval(t);
}
}
}
t = window.setInterval(function () {
isLoaded(t);
}, 700);
</script>
<style>
#wrapper{display:none;}
</style>
</head>
<body>
<img width="50" id="loading" style="left: 46%; top: 40%; position: absolute;" alt="loading" src="./images/loading.gif"/>
<div id="wrapper">your content</div>
</body>
</html>
代码1
代码1是一个移动端加载文件方式的简化版,每700ms去调用isLoaded函数,通过检测window.document.readyState的状态,判断是否页面资源加载完全。
如果是,隐藏loading的gif图标,显示页面内容,清除定时器。
言归正传,说到本文主题,页面加载状态,通过什么来判断呢?目前博主知道主要是两个,window.onload和window.document.readystate(亲测都兼容
IE7+,chrome,firefox),其他的没有测,不过应该都兼容,从两巨头w3c和whatwg的官方文档里都能找到。
1.先说window.onload,他的event handle event type是load.如图1:

图1(来源:https://html.spec.whatwg.org/#event-load)
当由window触发时,是当document加载完成,并且所有resource都加载完毕的时候触发。见代码2。
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
var onloadFunc = function(){
alert(document.getElementsByTagName("img")[0].complete);//true
};
window.onload = onloadFunc;
</script>
</head>
<body >
<div id="div1"><p>TODO write content</p>
</div>
<img src="http://dl.qqpy.sogou.com/qq.pinyin.cn_new/banner2.jpg?t=111" />
</body>
</html>
代码2
document.getElementsByTagName("img")[0].complete,所有浏览器支持,判断的是图片是否加载完成,这里弹出的是true。(参考)
2. 再说window.document.readystate。这个属性有三个值 loading /interactive/complete。官方解释,如图2:

图2(参考:https://html.spec.whatwg.org/#dom-img-complete)
document正在下载的时候,返回loading;document完成了解析,但是资源还在下载的时候,返回interactive;document加载完成,并且所有resource都加载完毕,返回complete.(亲测,ie7+,chrome,firefox都可以)。本文开篇所举的例子,即是使用complete判断document和其资源是否加载完毕。下边例子,进一步验证返回interactive的情况,见代码3。
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
var readyStateFunc = function () {
//loading /interactive/complete
if (window.document.readyState == ‘interactive‘) {
alert(document.getElementsByTagName("img")[0].complete);//false
clearInterval(id_of_setinterval);
}
};
id_of_setinterval = setInterval(readyStateFunc, 1);
</script>
</head>
<body >
<div id="div1"><p>TODO write content</p>
</div>
<img src="http://dl.qqpy.sogou.com/qq.pinyin.cn_new/banner2.jpg?t=111" />
</body>
</html>
代码3
document.getElementsByTagName("img")[0].complete返回的是false。说明,图片还没有加载完成。
3.window.onload和window.document.readystate==complete的触发先后顺序如何呢,经测试,onload先发生。