Search code examples
javascriptjqueryinternet-explorer-11mutation-observers

MutationObserver hangs in IE11


I am using MutationObserver to check when some nodes are removed and replaced by other new nodes to an element.

The following code works totally fine in Chrome, but on IE11 it just hangs.

If I change the addedNodes check with removedNodes, it works on IE11. I just don't understand why it hangs when I check for new nodes being added.

Any idea? I can't find any resources for this issue.

var nodeToObserve = document.querySelector('#targetNode');

var callback = function(mutations, observer) {
  for (var index = 0; index < mutations.length; index) {
    var mutation = mutations[index];
    if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
      console.log(mutation);
      break;
    }

  }
  observer.disconnect();
}
const observer = new MutationObserver(callback);

observer.observe(nodeToObserve, {
  childList: true, // target node's children
  subtree: true // target node's descendants
});
html, body {
  height: 100%;
}

#targetNode {
  border: 1px solid black;
  height: 100%;
}

.childNode {
  //height: 20px;
  background-color: blue;
  margin: 10px;
  padding: 10px;
}

.grandChildNode {
  height: 20px;
  background-color: red;
  margin: 10px;
}
<div id="targetNode">

</div>


Solution

  • You aren't incrementing the index in your for loop. Probably the results appear in a different order depending on the browser so the if statement will be triggered on some browsers but not others. Thus, the system will hang when the if statement isn't executed b/c of the infinite loop.