wumi_blog
wumi_blog copied to clipboard
document.readyState DOMContentLoaded事件 与 load事件
document.readyState 参考 Values
The readyState of a document can be one of following:
- loading
The document is still loading.
- interactive
The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.
- complete
The document and all sub-resources have finished loading. The state indicates that the load event has been fired.
When the value of this property changes a readystatechange event fires on the document object.
readystatechange as an alternative to DOMContentLoaded event
// alternative to DOMContentLoaded event
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
initApplication();
}
}
对于DOMContentLoaded事件
事件DOMContentLoaded和load的区别
他们的区别是,触发的时机不一样,先触发DOMContentLoaded事件,后触发load事件。
DOM文档加载的步骤为
- 解析HTML结构。
- 加载外部脚本和样式表文件。
- 解析并执行脚本代码。
- DOM树构建完成。//DOMContentLoaded
- 加载图片等外部文件。
- 页面加载完毕。//load
在第4步,会触发DOMContentLoaded事件。在第6步,触发load事件。 用原生js可以这么写
// 不兼容老的浏览器,兼容写法见[jQuery中ready与load事件](http://www.imooc.com/code/3253),或用jQuery
document.addEventListener("DOMContentLoaded", function() {
// ...代码...
}, false);
window.addEventListener("load", function() {
// ...代码...
}, false);
用jQuery这么写
// DOMContentLoaded
$(document).ready(function() {
// ...代码...
});
//load
$(document).load(function() {
// ...代码...
});