Mutation observer - DOM is changed by callback function

て烟熏妆下的殇ゞ 提交于 2019-12-11 03:18:16

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/24928635/mutation-observer-dom-is-changed-by-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!