Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - When are MutationObserver callbacks fired?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...