-
onload
的性能慢,会等DOM元素加载完毕,并且还会等到资源也加载完毕才会执行,而DOMContentLoaded
事件只会等到DOM元素加载完毕就会执行回调,但是IE8以下不支持,将addEventListener
监听事件换成attachEvent
,但是attachEvent
不兼容火狐谷歌,同时DOMContentLoaded
也不兼容IE,所以可用readyState
-
用法:
document.readyState
该属性返回以下值:
uninitialized - 还未开始载入
loading - 载入中
interactive - 已加载,文档与用户可以开始交互
complete - 载入完成
onreadystatechange
事件就是专门用于监听document.readyState
属性的改变的附代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
/*
window.οnlοad=function(){
// var res=document.querySelectorAll('div');
// console.log(res);
console.log('onload');//比较和DOMContentLoaded谁先打印
}
document.addEventListener('DOMContentLoaded', function () {
// var res = document.querySelectorAll('div');
// console.log(res);
console.log("DOMContentLoaded");//比较和onload谁先打印
})
*/
/*IE浏览器*/
document.attachEvent('onreadystatechange',function(){//attachEvent不兼容火狐谷歌
if(document.readyState=="complete"){
console.log('onreadystatechange');
}
})
</script>
</head>
<body>
<div></div>
<div></div>
</body>
</html>