119

I'm interested in using MutationObserver to detect if a certain HTML element is added anywhere in an HTML page. For example's sake, I'll say that I want to detect if any <li>'s are added anywhere in the DOM.

All the MutationObserver examples I've seen so far only detect if a node is added to a particular container. For example:

some HTML

<body>

  ...

  <ul id='my-list'></ul>

  ...

</body>

MutationObserver definition

var container = document.querySelector('ul#my-list');

var observer = new MutationObserver(function(mutations){
  // Do something here
});

observer.observe(container, {
  childList: true,
  attributes: true,
  characterData: true,
  subtree: true,
  attributeOldValue: true,
  characterDataOldValue: true
});

So in this example, the MutationObserver is setup to watch a very certain container (ul#my-list) to see if any <li>'s are appended to it.

Is it a problem if I wanted to be less specific, and watch for <li>'s over the entire HTML body like this:

var container = document.querySelector('body');

I know it works in the basic examples I've setup for myself... But is it not advised to do this? Is this going to result in poor performance? And if so, how would I detect and measure that performance issue?

I figured maybe there was a reason that all the MutationObserver examples are so specific with their targeted container... but I'm not sure.

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
  • Performance issues are specific to a given scenario. If your entire document only has a few simple elements I'm certain you won't have any issues. If you fear having performance issues, profile! – Amit Jul 27 '15 at 17:37
  • 11
    I have used plenty of `MutationObserver`s and had them recursively watch the entire DOM. I've personally never had a problem with performance. – Luke Jul 27 '15 at 17:44
  • 9
    The primary reason for the introduction of MutationObservers and the deprecation of MutationEvents is because MutationObservers are much faster because they aggregate changes together. We also use MutationObservers with `subtree: true` on large documents and it has never been an issue. – loganfsmyth Jul 27 '15 at 18:09
  • 1
    Why are you observing changes in attributes and character data? You say so yourself -- you want to observe possible additions of `li` elements? If something is a candidate for sub-optimal performance, I'd say asking for more events than you need, is that. – Armen Michaeli Apr 26 '19 at 18:52
  • As an example, Boomerang.js (https://github.com/akamai/boomerang), the web performance monitoring lib, is using a `MutationObserver` on the whole document to measure SPAs page load time. – JulienD Feb 13 '20 at 09:08
  • If you just want to detect if any
  • 's are added anywhere in the DOM. You don't need `attributes: true, characterData: true, attributeOldValue: true, characterDataOldValue: true`
  • – Chester Fung Jun 28 '23 at 07:10