把平时遇到的事件循环相关代码,整理在一起,方便更好的理解。
参考博文:
https://blog.csdn.net/duola8789/article/details/83314880
1. setTimeout 中的document.write
先看代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM加载顺序</title>
</head>
<body>
<p>1</p>
<script>
document.write('2')
</script>
<p>3</p>
<script>
window.onload = function () {
document.write('4');
document.write('5');
setTimeout(function () {
document.write('8')
}, 1000)
};
setTimeout(function () {
document.write('6')
}, 0);
setTimeout(function () {
document.write('7')
}, 1000)
</script>
</body>
</html>
执行结果:页面显示67。
原因:document.write(‘6’) 在执行时,重写了document,此时覆盖掉了还没有执行的onload 定义。
注意:如果document.write(‘6’)的延时小于100ms就会出现上面的结果,如果大于100ms的话(比如200ms),页面最终显示的就是45678
后续补充中…