How to define DOM监测
:
- Newly added DOM
- DOM property changes
- remove dom
There are usually two ways. Early use of DOM events to monitor node changes is no longer recommended. Currently recommended MutationObserver
.
1. DOM events
event | effect | Precautions |
---|---|---|
DOMNodeInsertedIntoDocument | Used to detect insertion of nodes | This event is only triggered when a Node is inserted into the Document |
DOMNodeInserted | Used to detect insertion of nodes | Triggered when Node is inserted into Document or non-Document |
DOMNodeRemovedFromDocument | Used to detect node removal | This event is only triggered when the Node is removed from the Document |
DOMNodeRemoved | Used to detect node removal | This event is only triggered when Node is removed from Document or non-Document |
DOMAttributeModified | Used to detect DOM property changes | |
DOMCharacterDataModified | Detect text changes of DOM nodes | |
DOMSubtreeModified | Used instead of (DOMAttributeModified, DOMCharacterDataModified, DOMNodeInserted, DOMNodeInsertedIntoDocument, DOMNodeRemoved, and DOMNodeRemovedFromDocument) | There is a bug in the IE9 environment, when the Node is inserted for the first time, this event will not be triggered immediately |
Here 非Document
refers to the scene where the node is not on the DOM tree. Such as node storage and memory, Code demo
Two, MutationObserver
MutationObserver
Provides the ability to monitor changes in its own nodes and child nodes, including addition, removal, and attribute changes. Example:
const callback = (mutationRecords) => {
};
const observer = new MutationObserver(callback);
const targetNode = document.querySelector("#node");
const option = {
subtree: false,
childList: false,
attributes: true,
attributeFilter: undefined,
attributeOldValue: false,
characterData: false,
characterDataOldValue: false,
};
observer.observe(targetNode, option);
configuration | Defaults | illustrate |
---|---|---|
subtree | false | Listen to all descendant nodes of the target node |
childList | false | Monitor the behavior of adding and removing child nodes of the target node |
attributes | false | Listen for changes in the attributes of the target node |
attributeFilter | undefined | When the value is an array, only detect changes in the value of the specified property. |
attributeOldValue | false | Whether to record the old value of the attribute |
characterData | false | Whether to monitor the changes of text nodes |
characterDataOldValue | false | Whether to log the old value of the text node |
3. Reference
- [^1] Event In JavaScript
- [^2] MutationEvent
- [^3] MutationObserver: observe()