What are some practical examples of MutationObserver use?
Asked Answered
T

1

2

The most confusing thing in this API is for me the reason why use it. I know ReactJS and RxJS and I'm used to the concept when view reacts to data change. So watching changes to DOM, which happens definitely after some mutations to data, I can't see much sense in it. So my question is when (not) use it?

Tubb answered 9/1, 2019 at 14:27 Comment(2)
It's needed when augmenting third-party libraries, which you can't control (and you don't want to intercept the standard DOM API), which is why it's used a lot in userscripts and browser extensions. If you don't need it in your workflow, don't use it, you're lucky.Elin
Do you want to have some code executed once? Then you don't need a mutation observer. Do you want to have some code executed any time a particular part of the DOM changes? Perhaps in regards to specific types of changes? Then you probably benefit from using a MutationObserver. Do you now know if you need a MutationObserver? It's likely that you don't. It's fairly evident when you do need that.Escaut
C
4

You're thinking of the problem with a situation where you are already one step ahead. If you are using React/RxJS then the actual value of MutationObserver will most likely be very small.

Even within this, however, there is a clear possibility to leverage this. Suppose you are attempting to use a library within your React application that is not explicitly built for it, and modifies the DOM in some way, but want to extend this further or capture something from it. The best example for this would be augmenting FancyGrid further.

Currently, in a component, you would invoke such a library in componentDidMount, the same way the component above is built. However, this is simply fire-and-forget - you don't know when it is done executing, you don't even know what is happening on the "outside".

Enter MutationObserver. With it, before binding such a library to an element, you can use an observer to be notified of when elements are created, track them, and track property changes. The simplest use case for this would be to make a spinner above a (particularly time-consuming on load) grid.

Calix answered 9/1, 2019 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.