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.
MutationObserver
s and had them recursively watch the entire DOM. I've personally never had a problem with performance.subtree: true
on large documents and it has never been an issue.li
elements? If something is a candidate for sub-optimal performance, I'd say asking for more events than you need, is that.MutationObserver
on the whole document to measure SPAs page load time.