// detect MSIE 9,10,11, but not Edge
ua=navigator.userAgent.toLowerCase();isIE=/msie/.test(ua);
function doStuff(){
//
}
if(isIE){
// play it safe, very few users, exec ur JS when all resources are loaded
window.onload=function(){doStuff();}
} else {
// add event listener to trigger your function when DOMContentLoaded
if(document.readyState==='loading'){
document.addEventListener('DOMContentLoaded',doStuff);
} else {
// DOMContentLoaded already loaded, so better trigger your function
doStuff();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOMContentLoaded , load</title>
<link href="http://localhost/public/css?sleep=5000" rel="stylesheet">
<!-- 5000 milliseconds after the URL request the server begins to respond -->
</head>
<body>
<img src="http://localhost/public/img?sleep=8000">
<!-- 8000 milliseconds after the URL request the server starts responding to the resource -->
<script>
document.addEventListener('DOMContentLoaded', () => {
console.log('DOMContentLoaded OKOK')
})
window.addEventListener('load', () => {
console.log('window load OK')
})
</script>
<script src="http://localhost/public/js?sleep=2000"></script>
<!-- 2000 milliseconds after the URL request the server begins to respond -->
</body>
</html>
DOMContentLoaded事件是在创建DOM时触发的(有关DOM的更多信息,请参阅链接1),而load事件是在加载DOM、CSSOM和所有其他资源时触发的。如果你没有Javascript,那么你的网页加载的顺序可能是这样的:
< / p >
或者用检查窗口的话来说,DOMContentLoaded事件将比load事件更早被触发(蓝线表示DOMContentLoaded,红线表示load事件):
< / p >