Understanding the MutationObserver API | by Emil Hein | May, 2022

This browser API provides us cool options you must use. It might sound scary, however I promise you it is not!

The DOM and the MutationObserver

The MutationObserver, is quite a bit just like the IntersectionObserver, as I described here. Apart from having the same title, the 2 APIs output could be very totally different. The MutationObserver is supported in most large browsers, and due to this fact you can begin using its performance.

So what’s all of it about?

Modifications within the DOM.

Whereas this sounds fairly easy, it is also extraordinarily helpful. With this characteristic, you possibly can detect if particular components are being inserted, eliminated, or the attributes of a component modifications.

With out utilizing this API, comparatively easy duties have a variety of edge circumstances, and efficiency may differ relying in your implementation. Utilizing an ordinary browser API can guarantee efficiency and stability out of the field.

  • You need to run some code if some components are inserted asynchronously
  • You need to detect a “page-change” in a single-page utility
  • You don’t have management of sure insertions of HTML components, to illustrate, from a third-party library
  • You will have a third-party ibrary applied on a website, and also you need to know when the location inserts a sure aspect on the web page

The final instance is the way in which I bought launched to the API.

In the identical approach that the IntersectionObserver API is a bit funky to work with, we are able to simply create a small wrapper that, for my part, makes it a bit smoother to work with. The native implementation requires three parameters:

  1. An HTML aspect (could be the whole physique)
  2. A configuration object that determines some specifics (see here)
  3. A callback operate that will probably be executed every time the API registers a change that meets your configuration params (1 and a pair of)
MutationObserver wrapper

I’m defaulting the configuration and the aspect to test within the above wrapper. What this configuration does is watch the whole doc physique for modifications. subtree: true will be sure that we glance by means of nested insertions or deletions.

In the event you already know a subelement the place you need to search for modifications, it is extra performant to present a extra particular selector than doc.physique.
For simplicity, the above wrapper solely wants a callback operate that will probably be triggered every time any aspect is modified.

MutationObserver callback operate

This may look a bit nested and scary, however don’t thoughts that for now.
The above will test for all nodes added to the DOM. If the node has an id=’color-node’, it would wait 200ms and alter the background to orange.

An instance

Now, to illustrate we’re the producers of a third-party library that modifications the div components with a selected id to a sure coloration after they’re inserted into the location. Now, we’ve got no management over how the location is applied. It could be a SPA or a WordPress website.

The positioning may insert the weather utilizing their very own JavaScript or one other library for it.

For simplicity’s sake, let’s assume the location inserts a selected node in a daily interval. Now our dummy library will change the background coloration of the inserted nodes.

A easy implementation, altering the colour as components are inserted

Within the above instance, I’m simulating that the location inserts 9 div components with an interval of 500ms. In actual life, that’s unlikely to occur. However that’s the great thing about the MutationObserver. It would set off your callback operate every time a component is inserted, deleted, or modified.

Be aware: As with the IntersectionObserver, it is essential to make use of the disconnect methodology whenever you not want to subscribe to mutations within the DOM.

SPA URL change

In one other small use case, we use the MutationObserver to detect web page modifications in a single-page utility. Now, since they don’t do an actual browser web page change however use inside routing, our script won’t be loaded and executed like on a “regular” web site.

With the MutationObserver, we are able to search for modifications within the DOM (a SPA router change) and test the location.href towards the earlier to resolve if the SPA has modified its view. After this, we must always rerun our core code logic. A easy instance may seem like this:

Detect change in SPA URL

As somebody who maintains a library applied on many websites, utilizing the MutationObserver helps us have a unified API for dealing with asynchronous insertions or deletions within the DOM.

In our case, we have to react every time the location inserts a selected div aspect.

If a brand new div aspect meets a set of standards, we are going to insert our “product” into that div aspect.

Now, because the MutationObserver triggers our callback on all insertions, it doesn’t matter if the shopper has an infinite scroll that retains including components or if it occurs by the clicking of a button.

Along with the IntersectionObserver API, it’s tremendous simple to deal with sure DOM issues with out implementing a variety of customized code.

Each APIs have been out there for fairly a while, however I really feel adoption remains to be fairly low.

It could be due to previous Stack Overflow solutions or their scary names.

Thanks for studying! Keep tuned for extra.

More Posts