假设我有这样的代码
<html><body>
<bunch of html tags...>
<script>
function myF()={};
setTimeout(myF, 100);
</script>
<lots of more html goes here.....></body></html>
据我了解,脚本将在解析 html 时进行评估。但是,在这种情况下,我们有一个 setTimeout,然后是大量的 html 解析。超时什么时候开始调用?是否需要等到所有 html 解析完成后才最终调用 myF,还是在超时事件发生时调用 myF,即使还有更多的 html 解析要完成?
最佳答案
不,setTimeout() 不一定必须等待 DOMContentLoaded
如果是这样,我们就不需要 DOMContentLoaded
事件,但如果这还不足以说服您,以下是确凿的证据:
<script>
window.addEventListener('load', function() {
alert("Window Loaded");
});
document.addEventListener('DOMContentLoaded', function() {
alert("DOM Content Loaded");
});
setTimeout(function() {
alert(typeof jQuery == 'function' ? 'jQuery Loaded' : 'jQuery Not Loaded');
}, 15);
</script>
<p>This content will be loaded before jQuery is fetched.</p>
<script>
document.write('<script src="https://code.jquery.com/jquery-3.2.1.min.js?' + Math.random() + '" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></' + 'script>');
</script>
<script>
alert('Loaded after <script src="jquery.min.js">');
</script>
<p>This content will not be loaded until after jQuery is fetched.</p>
如果它必须等待 DOMContentLoaded
, 你会看到
Loaded after <script src="jquery.min.js">
DOM Content Loaded
Window Loaded
jQuery Loaded
然而(至少对我而言),大部分时间,输出是
jQuery Not Loaded
Loaded after <script src="jquery.min.js">
DOM Content Loaded
Window Loaded
虽然HTML的解析是单线程的,但是在<script>
时还是会被阻塞没有async
和 <link>
必须暂停以从 URL 获取资源并分别执行脚本或样式表,这意味着 DOMContentLoaded
之间存在竞争条件事件和 setTimeout(function() { ... }, 15)
.
关于javascript - setTimeout 何时开始在内联 <script> 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712379/