When are MutationObserver callbacks fired?

淺唱寂寞╮ 提交于 2019-11-28 06:47:19

MutationObservers are fired asynchronously but 'soon', which means they fire before other things in the queue, such as layout, paint, or triggered events.

This ameliorates the loss of synchrony, because you don't have to worry about screen flashing or other bad things happening before your observer gets a chance to react.

In developer notes, they talk about an 'end-of-microtask' timing model. I agree this is poorly documented.

FelisCatus

I'm going to answer my own question two years later according to the updated DOM spec from WHATWG.

As shown in the spec:

To queue a mutation observer compound microtask, run these steps:

  1. If mutation observer compound microtask queued flag is set, terminate these steps.
  2. Set mutation observer compound microtask queued flag.
  3. Queue a compound microtask to notify mutation observers.

While "Queuing a compound microtask" links to a section in the HTML spec explaining the microtask queue model.

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.

For further understanding of the event loop and processing model, the Event Loop section of the HTML spec would be perfect.

Personally, I'm glad to see that MutationObservers are part of the standard and have a well-documented and consistent timing model. With MutationObservers supported in most modern browsers, I think they are solid for production use now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!