问题描述
我知道在DOM更改后的某个时候,MutationObservers回调可能会被调用。但问题是:这些回调的时间是多少?
回调是否进入浏览器的事件队列?如果是,他们什么时候进入队列?
I know that MutationObservers callbacks may get called sometime after the DOM change. But the question is: What is the timing of these callbacks?Do the callbacks enter the event queue of the browsers? If so, when do they enter the queue?
是否回调:
- 在DOM突变发生之后立即调用,一旦处理DOM的函数完成,
- 调用
- 调用堆栈是空的,
- 在DOM突变发生后立即进入,
- 只要处理DOM的功能完成,或
- 在某些其他时间?
- called immediately after the DOM mutation take place,
- called as soon as the function that manipulate DOM finishes,
- called as soon as the call stack is empty,
- enqueued immediately after the DOM mutation take place,
- enqueued as soon as the function that manipulate DOM finishes, or
- at some other time?
例如,如果执行以下代码段(使用):
For example, if the following piece of code is executed (with setZeroTimeout defined here):
var target = document.body;
new MutationObserver(function(mutations) {
console.log('MutationObserver');
}).observe(target, {
attributes: true,
childList: true,
characterData: true
});
// Post message
setZeroTimeout(function () { console.log('message event'); });
// DOM mutation
target.setAttribute("data-test", "value");
应该在message event之前或之后打印MutationObserver
或者是否实现定义?
Should "MutationObserver" be printed before "message event" or after it?Or is it implementation-defined?
在Chromium 26上的消息事件之前,我收到了MutationObserver,尽管DOM突变是在消息发布之后。也许这表明MutationObserver回调是不使用事件队列。
I'm getting "MutationObserver" before "message event" on Chromium 26, though the DOM mutation is after message posting. Maybe this is indicating that MutationObserver callbacks are not using the event queue.
我已经针对HTML规范,DOM规范或浏览器实现文档进行了搜索,但是我没有发现任何与此行为有关的问题。
I have googled for HTML specification, DOM specification or browser implementation documents, but I didn't found anything related to this behavior.
有关MutationObservers回调时间的任何说明或文档?
Any explanation or documentation on the timing of MutationObservers callbacks please?
推荐答案
根据更新的DOM规范
如规范中所示:
- 如果突变观察者复合微任务排队的标志被设置,终止这些步骤。
- 设置突变观察者复合微任务排队标志。
- 将复合微任务排队到fy突变观察者。
虽然排队复合微任务链接到,解释微任务队列模型。
While "Queuing a compound microtask" links to a section in the HTML spec explaining the microtask queue model.
因此,我们可以得出结论, MutationObserver
回调被触发为微任务,这确实比任务队列任务早于上面的@Scott Miles的答案。
Therefore, we can conclude that MutationObserver
callbacks are fired as microtasks, which are indeed sooner than the task queue tasks as suggested by the answer of @Scott Miles above.
为了进一步了解事件循环和处理模型, HTML规范将是完美的。
For further understanding of the event loop and processing model, the Event Loop section of the HTML spec would be perfect.
个人而言,我很高兴看到 MutationObserver
是标准,并具有良好的文件和一致的时间模型。使用 MutationObserver
,我认为现在这些产品已经很好用了。
Personally, I'm glad to see that MutationObserver
s are part of the standard and have a well-documented and consistent timing model. With MutationObserver
s supported in most modern browsers, I think they are solid for production use now.
这篇关于MutationObserver回调何时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!