Mutation Observer

What is Mutation Observer and how to use it?

Introduction Mutation Observer

Mutation Observer is a built-in object that observes DOM Changes and calls or fires a callback function to react to the changes in the DOM Tree.

We can say that a Mutation observer will allow you to keep the watch on Element changes in DOM.

How To Use Mutation Observer:

Step 1

  • Create a callback function that will execute DOM Changes.
  • Code:
    const callback = function (mutationsList, observer) {
    		// 
    		}

Step 2

  • Create an Observer instance and pass it to the callback function.
  • Here, We will use the MutationObserver() constructor to create an object.
  • Code:
    let observer = new MutationObserver(callback);

Step 3

  • Next call observe() function to observe DOM changes.
  • Code:
    observer.observe(targetNode, Config);
  • targetNode:
    • This is the element on which the observer will keep watch when any changes are detected.
  • config:
    • It’s a simple boolean option “What kind of changes to detect”
  • Example:
    • childList – Detect changes in direct children of targetNode.
    • subtree – Detect changes in all descendants of the node.
    • attributes – Detect Attribute changes.
    • attributeFilter – It provides a filter to detect particular attribute changes.
    • characterData – which is used to observe the changes of text content.
    • attributeOldValue – If it’s true, then It’ll pass old and new attribute data to the callback function, else pass only new data.
    • characterDataOldValue – If it’s true, then It’ll pass old and new characterData to the callback function, else pass only new data.

Step 4

  • pass in the target node and configuration
  • Code:
    observer.observe(targetNode, config);

Hire Frontend Developers - Bigscal

Code Block:

// define the target node
		var targetNode = document.body;

		// configuration of the observer
		const config = { childList: true, characterData: true, subtree: true, attributes: true, };

		// callback function
		const callback = function (mutationsList, observer) {
		console.log('Changes Detected');
		};

		// Create observer instance
		const observer = new MutationObserver(callback);

		// pass in the target node and configuration
		observer.observe(targetNode, config);

disconnect() Method

  • MutationObserver provides a disconnect() function to stop observing.
  • Code:
    observer.disconnect();

Where is it required?

  • You want to let your web app visitor know that the page he’s on has changed.
  • You’re working on a JavaScript framework that dynamically loads modules based on DOM(Document Object Model) changes.
  • When you are trying to implement undo/redo functionality. By using mutation observer, you know at any given point what changes have been made, so you can easily undo them.
  • You can continuously observe the dynamic content updating in DOM(Document Object Model).

Alternatives :

  • 1. Polling

    • You can create a task that checks for updates regularly using the browser setInterval WebAPI. Naturally, the performance of the web app/website suffers greatly as a result of this strategy.
  • 2. MutationEvents

    • Mutation events are fired on every single change in the DOM But It causes performance issues and also Modern Browsers do not support MutationEvents.
  • 3. CSS animations

    • The basic concept is to construct an animation that is triggered once an element is added to the DOM. The animationstart event is emitted when the animation begins; if you’ve attached an event handler to that event, you’ll know exactly when the element is added to the DOM. The duration of the animation should be so short that it is virtually undetectable to the user.

First, we need a parent element, inside which, we’d like to listen to node insertions:

<div id=”target-element”></div>

		To get a handle on node insertion, To master node insertion, we'll need to put up a series of keyframe animations that will begin when the node is inserted:

		@keyframes node-Inserted { 
		from { opacity: 0.99; }
		to { opacity: 1; } 
		}

After you’ve built the keyframes, you’ll need to apply the animation to the objects you want to listen for. Small durations are important since they reduce the animation footprint in the browser:

#target-element * {
		animation-duration: 0.001s;
		animation-name: nodeInserted;
		}

This adds the animation to all of the target-child element’s nodes. The insertion event will fire after the animation is finished.

We’ll need a JavaScript function to act as a listener for events. The initial event.animationName check must be performed within the function to guarantee that the animation is the one we want.

var insertionListener = function(event) { 
		if (event.animationName === "nodeInserted") {
		console.log("Node Inserted: " + event.target);
		}
		}

Now, add the event listener to the parent:

document.addEventListener(“animationstart”, insertionListener, false);

Over the above-mentioned solutions, MutationObserver has a lot of advantages. In essence, it covers every possible change in the DOM, and it’s far more efficient because it fires the changes in batches. Furthermore, all major modern browsers support MutationObserver.

Reference Link:

https://javascript.info/mutation-observer

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply