javascript - setTimeout 何时开始在内联 <script> 中执行

标签 javascript html timeout

假设我有这样的代码

<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 何时开始在内联 &lt;script&gt; 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712379/

相关文章:

scala - 有什么方法可以记录 akka 超时并提供有关错误位置的更多信息?

java - 文件上传慢 : Can I remove file attachment from multipart POST data on the fly and just submit form text fields?

html - 响应式 CSS div 相互重叠

javascript - 在 iPad 上触摸滚动增量值

php - Mysql中存储的特殊字符

html - CSS 未应用于使用 WebView 的 OSX 应用程序

linux - 在超时内给出命令错误

C++ 下载文件 - 如果不可用,增加 RAM 使用率 1mb/s

javascript - 通过伪经典实例化(JavaScript)掌握原型(prototype)继承

javascript - 如何嵌套promise.all