4

How can I make an observing instance of MutationObserver to ignore some DOM changes, which are caused by my code? For example (with jQuery):

//initialize MutationObserver
var mo = new MutationObserver(mutations => console.log(mutations));
mo.observe(document.body, {attributes: true, subtree: true, characterData: true, attributeOldValue: true, characterDataOldValue: true, childList: true});
//case 1: perform a removal
$('.someDiv').remove();
//in this case an action is logged by MO
//case 2: perform a removal with a disconnected MO
mo.disconnect();
$('.someDiv').remove();
mo.observe(document.body, {...});
//in this case an action is logged again!

In both cases MO logs all the changes I have done to DOM. There is the only way I came up with:

//case 3: perform a removal with a disconnected MO, turning on after a timeout
mo.disconnect();
$('.someDiv').remove();
setTimeout(() => mo.observe(document.body, {...}), 500); //pseudo
//in this case MO skips an action above

But it is not the best solution of that problem, because there can be some other actions caused on page by user during the timeout, or the MutationObserver's callback can be called in some time later than the timeout does.

asked Jun 24, 2017 at 12:08
0

1 Answer 1

9

MutationObserver's callback is invoked asynchronously so the changes made by the currently executed code are accumulated and submitted only when it's finished.
This is how JavaScript event loop works.

If you disconnect and reconnect in the same event, you need to deplete the queue explicitly:

mo.disconnect();
mo.takeRecords(); // deplete the queue
..............
mo.observe(......);
answered Jun 29, 2017 at 4:53
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.