You can't understand MutationObserver in JavaScript. Do you dare to write proficient in JavaScript on your resume?

1. MutationObserver interface

The MutationObserver interface, which was added to the DOM specification a while ago, can execute callbacks asynchronously when the DOM is modified. Use MutationObserver to observe the entire document, part of the DOM tree. In addition, you can observe changes in element attributes, child nodes, text, or any combination of the first three.

2. Basic usage of MutationObserver

An instance of the MutationObserver interface is created by calling the MutationObserver constructor and passing in a callback function:

let observer = new MutationObserver(() => console.log('DOM was mutated!'));

1. observe() method

The newly created MutationObserver instance is not associated with any part of the DOM. To use the observe() method, this method receives the required parameters: the DOM node to observe, and a MutationObserverInit object.
The MutationObserverInit object is used to control which changes are observed, and is a dictionary of configuration options in the form of key-value pairs.
For example, the following code creates an observer and configures it to observe property changes on elements:

let observer = new MutationObserver(() => console.log('<body> changed!'));
observer.observe(document.body,{
    
    attributes:true});

Execute the above code, any property changes on the element will be discovered by this MutationObserver instance, and then the registered callback function will be executed in one step.

2. Callback and MutationRecord

Each callback receives an array of MutationRecord instances. The MutationRecord instance contains what changed, and what part of the DOM was affected.

3. Disconnect() method

By default, as long as the observed element is not garbage collected, the callback of the MutationObserver will be executed in response to the DOM change event. To terminate the callback early, you can call the disconnect() method.

4、复用MutationObserver

3. MutationObserverInit and observation range

The MutationObserverInit object is used to control the observation range of the target node. In layman's terms, the events that the observer can observe include attribute changes, text changes, and child node changes.

4. Asynchronous callback and record queue

The MutationObserver interface is designed for performance considerations. Its core is the asynchronous callback and record queue model. In order not to affect performance when a large number of change events occur, the information of each change (determined by the observer instance) will be saved in the MutationRecord instance. , and then added to the record queue. This queue is unique to each MutationObserver instance and is an ordered list of all DOM change events.

5. Performance, memory and garbage collection

MutationEvent, described in the DOM Level 2 specification, defines a set of events that fire on various DOM changes. Due to the implementation mechanism of browser events, this interface has serious performance problems. Therefore, DOM Level 3 deprecated these events. The MutationObserver interface is a more practical and performant solution designed to replace these events.
Delegating change callbacks to microtasks ensures that events fire synchronously, while avoiding the chaos that ensues. The record queue implemented for MutationObserver ensures that even if change events are fired in bursts, it doesn't slow down the browser significantly.
In any case, MutationObserver is still not without cost, so it is important to understand when to avoid this situation.

1. Reference to MutationObserver

The reference relationship between the MutationObserver instance and the target node is asymmetric. MutationObserver holds a weak reference to the target node to observe. Because it is a weak reference, it will not prevent the garbage collector from reclaiming the target node.
However, the target node has a strong reference to the MutationObserver. If the target node is removed from the DOM and then garbage collected, the associated MutationObserver will also be garbage collected.

2. Reference to MutationRecord

Each MutationRecord instance in the record queue contains at least one reference to an existing DOM node. If the change is of type childList, it will contain references to multiple nodes. The default behavior of the record queue and callback processing is to drain this queue, process each MutationRecord, and then let them go out of scope and be garbage collected.
Sometimes it may be necessary to keep a complete record of changes to an observer. Saving these MutationRecord instances will also save the nodes they refer to, thus hindering the garbage collection of these nodes. If you need to release memory as soon as possible, it is recommended to extract the most useful information from each MutationRecord and save it to a new object. Finally discard the MutationRecord.

6. JavaScript Mind Map

insert image description here


Previous: Mastering JavaScript? How much do you know about JavaScript memory and performance issues?
Next: Summary of Java learning routes, brick movers counterattack Java architects

Pay attention to the public number: Nezha programming

Nezha programming updates high-quality articles every week. After paying attention, reply to [CSDN] to receive Java mind maps, Java learning materials, and massive interview materials.

 

Add me WeChat: 18525351592

Pull you into the technical exchange group, there are many technical bigwigs in the group, exchange technology together, advance together, enter the big factory together, and also buy technical books for free~~

おすすめ

転載: blog.csdn.net/guorui_java/article/details/123610958