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.
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(......);