DOMContentLoaded 事件和任务队列

DOMContentLoaded event and task queue

听说事件循环处理模型中有3个队列有任务

  1. MacroTaskQueue : 这个队列有setTimeout, setInterval等回调函数
  2. MicroTaskQueue : 这个队列有promise, mutationOberver 等回调函数
  3. AnimationFrameQueue : 这个队列有requestAnimationFrame的回调函数。

所以,我想知道的是

var a = 10;
console.log(a);

setTimeout(function b() { console.log('im b'); }, 1000);

在此代码中,

var a = 10;
console.log(a);

此代码是否也在 MacroTaskQueue 或 MicroTaskQueue 中排队?

或者仅 b 在(分钟)1000 毫秒后在 MacroTaskQueue 中排队?

我在黑洞里。请帮助我:D

你所说的“MacroTaskQueue”实际上是由几个task-queues, where tasks are being queued. (Note that the specs only use multiple task-sources, there could actually be a single task-queue). At the beginning of the event-loop processing组成的,浏览器会从哪个任务队列中选择下一个“主”任务来执行。重要的是要理解这些任务可能根本不意味着任何 JavaScript 执行,JS 只是浏览器所做的一小部分。

microtask-queue 将在单个 event-loop 迭代期间多次访问和清空。例如每次 JS call stack has been emptied (i.e after almost every JS callback execution) and if it wasn't enough there are fixed "Perform a microtask checkpoint" points in the event-loop processing model.

虽然类似于队列,但动画帧回调实际上存储在有序映射中,而不是队列本身,这允许从这些回调之一“排队”新回调,而不会在之后立即出队。更重要的是,还执行了很多其他回调 at the same time,例如滚动事件、调整大小事件、Web 动画步骤 + 事件、ResizeObserver 回调等。但是这个“更新渲染”步骤只会偶尔发生一次,一般以显示器刷新率。

但是,这并不能说明 DOMContentLoaded。

Who fires DOMContentLoaded event ?

此事件作为文档解析步骤的一部分在 "the end" section. The browser has to first queue a task on the DOM manipulation task-source. This task will then eventually get selected by the browser as part of the first step of the event-loop. And once this task's steps will be executed, the event will be fired and dispatched on the Document. That's only as part of this dispatch an event algorithm that the browser will invoke and inner-invoke until it calls 我们的侦听器回调中触发。
请注意,此文档解析步骤本身作为一项任务非常有趣,因为这是最明显的地方,您将在“主要”任务中交错多个 microtask-checkpoints(例如,在每个