dakov
dakov

Reputation: 1139

Mutation observer - DOM is changed by callback function

is there a way, how to force mutation observer to ignore DOM changes cause by callback function?

Right now I have:

var config = { attributes: true, childList: true, characterData: true };
var target = document.body;
var timer;

// create an observer instance
var observer = new MutationObserver(function(mutations) {

   // fired when a mutation occurs
   timer = setTimeout(function () {

      _3rd_party_callback();


   }, 500);  

});

observer.observe(target, config);

Problem is that, _3rd_party_callback callback cause DOM change, so it never stops. As its names says, It's third party function and I can't change (actually its DOM manipulating is its purpose).

So what I do is to disconnect and start observer before and after the function is called in callback, respectively.

  observer.disconnect()
  _3rd_party_callback();
  observer.observe(target, config);

It seems to work, but I'm afraid, that thanks to asynchronous handeling of the event I might have observer disabled, when others changes are made and miss them.

It's quite unlikely that there's a way to separate changes from page itself and the callback, but I'll give it a try.

Upvotes: 5

Views: 2010

Answers (1)

megawac
megawac

Reputation: 11353

Your idea will work if observer will only observe target and nothing else. It's not a particularly efficent solution as you'll have to set up the hooks again each time you reset the observable but it will work.

observer.disconnect()
_3rd_party_callback();
observer.observe(target, config);

There is 0 chance that you'll miss an event caused by anything outside of _3rd_party_cb due to all DOM changes occuring in the main event loop. So you disconnect your observer, call the 3rd party code then reconnect it --- there is no step in between for the DOM to change. However if 3rd party code defers a change through, e.g. setTimeout(messupthedom, 0) you'll still pick up these changes in your observable.

Upvotes: 5

Related Questions