MutationObserver provides developers with the ability to respond appropriately to changes in the DOM tree within a range. The API is designed to replace the Mutation events introduced in the DOM 3 event specification.

– the MDN

1. An overview of the

  • An interface to monitor DOM changes

    The MutationObserver is notified when the monitored DOM changes and fires a predefined callback function.

  • Similar to an event, but asynchronously fired

    When adding monitoring, the observer function on the MutationObserver is similar to addEventListener, but unlike the latter’s synchronous trigger, the MutationObserver is asynchronously triggered. This is to avoid frequent calls to the callback function due to frequent DOM changes, causing the browser to stall.

2. MutationObserver constructor

This constructor instantiates a new MutaionObserver and specifies the callback function when DOM changes are triggered:

var observer = new MutationObserver(callback);
Copy the code

The callback takes two arguments. The first argument is an array containing all the MutationRecord objects (more on that later, but don’t worry), and the second argument is the MutationObserver instance itself.

3. MutationObserver instance method

3.1 Observe(Node target, optional MutationObserverInit options);

Add the DOM node to the MutationObserver instance to observe and configure which changes to observe with an optional options parameter, an object named MutationObserverInit.

Here are the properties of the MutationObserverInit object and their descriptions:

attribute type describe
childList Boolean Whether to observe changes in child nodes
attributes Boolean Whether to observe property changes
characterData Boolean Whether the node content or node text changes
subtree Boolean Whether to observe all offspring node changes
attributeOldValue Boolean Observe whether the attribute value before the change is recorded when the attributes change
characterDataOldValue Boolean Observe whether to record the property value before the characterData change
attributeFilter Array Represents a specific attribute (such as [‘class’,’ SRC ‘]) that needs to be observed and is ignored if the attribute changes outside this array

Note:

  • You cannot observe subtree changes in isolation; you must specify one or more of childList, Attributes, and characterData.
  • Adding the same MutationObserver to the same DOM node multiple times is invalid and the callback function will be fired only once. However, if different Options objects are specified (that is, different changes are observed), they are treated as different MutationObservers. (Does it really feel like addEventListener?)

3.2  disconnect();

This method is used to stop the observation. The callback function is no longer triggered if the DOM node changes.

observer.disconnect();
Copy the code

Continuing the analogy, the disconnect function is similar to removeEventListener, except that disconnect is more crude (cannot pass a parameter configuration) and will stop all observations on the MutationObserver instance.

3.3  takeRecords();

This method clears the change record and returns an array of MutationRecord objects. MutationRecord is back. What is it?

In fact, each time the DOM changes, a change record is generated that corresponds to a MutationRecord object. Here are the properties of the MutationRecord object and their descriptions:

attribute type describe
type String Depending on the change type, the value is attributes, characterData, or childList
target Node The DOM node that changed
addedNodes NodeList The added node, or null
removedNodes NodeList Deleted node, or null
previousSibling Node The previous sibling of the node being added or removed, or null
nextSibling Node The second sibling of the node that was added or removed, or null
attributeName String The local name of the changed property, or null
attributeNamespace String The namespace of the changed property, or null
oldValue String If type is attributes, the value of the attribute before the attribute change is returned; If the type is characterData, the text data before the change of the object is returned. If type is childList, null is returned

In fact, the principle of MutationObserver is to wait for a script task to complete, store all the change records (all MutationRecord objects) generated during the process into an array, and then process the array in a unified way. The array, which contains all the changes, will be the first argument to the callback function. Here is an example of a callback function that handles the array:

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});
Copy the code

4. The compatibility

The MutationObserver was introduced in DOM Level 4, and its compatibility is shown below:

References:

MDN MutationObserver

JavaScript Standard Reference Tutorial (Alpha) — MutationObserver

DOM
JavaScript

Adhere to the original technology sharing, your support will encourage me to continue to create!

Scan the QR code to share this article