考虑以下代码:
<head>
<style>
.box{
background-color:red;
height:150px;
width:150px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var start = new Date();
while(true) {
var now = new Date();
if (now-start > 10000)
break;
}
console.log('main thread finished');
</script>
</body>
令我惊讶的是 DOM 延迟了 10 秒加载(.box 矩形在 10 秒后出现!)。因为它排在第一位( <div class="box"></div> )
,为什么要等待后面的脚本?有什么合理的解释吗?
谢谢
最佳答案
"Scripts without async or defer attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page." -- from MDN.
因此您的脚本将停止解析 10 秒。更不用说渲染页面了。基本上这样做是为了支持从执行脚本中立即修改 html。例如,如果您的脚本调用 document.write('More html')
,它将影响解析。
顺便说一句,执行脚本可以访问已经解析的DOM结构。考虑以下示例。
<div class="box">Affected</div>
<script>
[].forEach.call(document.querySelectorAll('.box'), function(box){
box.innerText += '... modified';
});
</script>
<div class="box">Not</div>
关于javascript - DOM 加载被后续脚本阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35500115/