43

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?

Are the callbacks:

  • 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");

Should "MutationObserver" be printed before "message event" or after it? Or is it implementation-defined?

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.

I have googled for HTML specification, DOM specification or browser implementation documents, but I didn't found anything related to this behavior.

Any explanation or documentation on the timing of MutationObservers callbacks please?

4

2 に答える 2

23

MutationObserver は非同期で起動されますが、「すぐに」起動されます。つまり、レイアウト、ペイント、またはトリガーされたイベントなど、キュー内の他のものよりも先に起動されます。

これにより、オブザーバーが反応する機会を得る前に画面の点滅やその他の悪いことが起こることを心配する必要がないため、同期の喪失が改善されます。

開発者ノートでは、「マイクロタスクの終了」タイミング モデルについて説明しています。これは十分に文書化されていないことに同意します。

于 2013-04-08T21:45:25.867 に答える