By dakov

2014-07-24 08:26:13 8 Comments

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 () {


   }, 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.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.


@megawac 2014-07-28 21:18:22

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.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.

Related Questions

Sponsored Content

43 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 774636 View
  • 2820 Score
  • 43 Answer
  • Tags:   javascript jquery

11 Answered Questions

[SOLVED] How to access the correct `this` inside a callback?

40 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

32 Answered Questions

[SOLVED] Remove all child elements of a DOM node in JavaScript

  • 2010-10-17 20:51:00
  • Polaris878
  • 924588 View
  • 921 Score
  • 32 Answer
  • Tags:   javascript dom

27 Answered Questions

1 Answered Questions

16 Answered Questions

[SOLVED] How do I find out which DOM element has the focus?

  • 2009-01-30 20:21:31
  • Tony Peterson
  • 680487 View
  • 1341 Score
  • 16 Answer
  • Tags:   javascript dom

32 Answered Questions

[SOLVED] How can I change an element's class with JavaScript?

  • 2008-10-12 20:06:43
  • Nathan Smith
  • 2668788 View
  • 2843 Score
  • 32 Answer
  • Tags:   javascript html dom

1 Answered Questions

[SOLVED] Disconnect Mutation Observer from Callback Function

Sponsored Content