Home > Web Front-end > H5 Tutorial > Detailed explanation of HTML5 new features Mutation Observer code

Detailed explanation of HTML5 new features Mutation Observer code

黄舟
Release: 2017-03-30 11:29:32
Original
2646 people have browsed it

1. Overview

Mutation Observer is an interface that monitors DOM changes. Mutation Observer will be notified when any changes occur in the DOM object tree.

Conceptually, it is very close to Event. It can be understood that when the DOM changes, the Mutation Observer event will be triggered. However, it is fundamentally different from events: events are triggered synchronously, which means that when the DOM changes, the corresponding event will be triggered immediately; Mutation Observer is triggered asynchronously. After the DOM changes, it will not be triggered immediately, but will wait until Triggered after all current DOM operations are completed.

This design is to cope with frequent DOM changes. For example, if you continuously insert 1000 paragraphs (p elements) into the document, 1000 insertion events will be triggered continuously, and the callback function of each event will be executed, which is likely to cause the browser to freeze; The Mutation Observer is completely different. It will only be triggered after all 1000 paragraphs have been inserted, and it will only be triggered once.

Note: You can see the log in the console

Mutation Observer has the following characteristics:

  • It waits for all script tasks to be completed before running , that is, the asynchronous method

  • is used to encapsulate the DOM change record into an array for processing instead of processing the DOM changes individually one by one.

  • It can observe all changes that occur in DOM nodes, or it can also observe a certain type of changes

Currently , Firefox(14+), Chrome(26+), Opera(15+), IE(11+) and Safari(6.1+) support thisAPI. When Safari 6.0 and Chrome 18-25 use this API, you need to add the WebKit prefix (WebKitMutationObserver). You can use the following expression to check whether the browser supports this API.

var MutationObserver = window.MutationObserver ||
    window.WebKitMutationObserver ||
    window.MozMutationObserver;var mutationObserverSupport = !!MutationObserver;
Copy after login

2. Usage method

First, use the MutationObserver constructor to create a new instance and specify the callback function of this instance.

var observer = new MutationObserver(callback);
Copy after login

2.1 observer method

The observer method specifies the DOM element to be observed and the specific changes to be observed.

var article = document.querySelector('article');
var options = {    
'childList': true,    
'arrtibutes': true};

observer.observer(article, options);
Copy after login

The above code first specifies that the DOM element to be observed is article, and then specifies that the changes to be observed are changes in child elements and changes in attributes. Finally, pass these two qualifications as parameters into the observer method of the observer object.

The DOM changes observed by MutationObserver (that is, the option object in the above code) include the following types:

  • childList: changes in child elements

  • attributes: changes in attributes

  • characterData: changes in node content or node text

  • subtree: all subordinate nodes (including Changes in child nodes and child nodes of child nodes)

Which type of change you want to observe, just specify its value as true in the option object. It should be noted that subtree changes cannot be observed alone, and one or more of childList, attributes, and characterData must be specified at the same time.

In addition to the change type, the option object can also set the following attributes:

  • attributeOldValue: the value is true or false. If true, it means that the attribute value before the change needs to be recorded.

  • characterDataOldValue: The value is true or false. If true, it means that the data value before the change needs to be recorded.

  • attributesFilter: The value is an array, indicating the specific attributes that need to be observed (such as ['class', 'str']).

2.2 disconnect method and takeRecord method

disconnect method is used to stop observation. When corresponding changes occur, the callback function will no longer be called.

observer.disconnect();
Copy after login

The takeRecord method is used to clear the change record, that is, no longer process unprocessed changes.

observer.takeRecord
Copy after login

2.3 MutationRecord object

Every time the DOM object changes, a change record will be generated. This change record corresponds to a MutationRecord object, which contains all information related to the change. An array composed of mutation objects processed by Mutation Observer.

The MutationRecord object contains DOM-related information and has the following attributes:

  • type: observed change type (attribute, characterData or childList).

  • target: The changed DOM object.

  • addedNodes: Newly added DOM objects.

  • removeNodes: Removed DOM objects.

  • previousSibling:前一个同级的DOM对象,如果没有则返回null。

  • nextSibling:下一个同级的DOM对象,如果没有就返回null。

  • attributeName:发生变动的属性。如果设置了attributeFilter,则只返回预先指定的属性。

  • oldValue:变动前的值。这个属性只对attribute和characterData变动有效,如果发生childList变动,则返回null。

3、实例

3.1 子元素的变动

下面的例子说明如果读取变动记录。

var callback = function(records) {
    records.map(function(record) {
        console.log('Mutation type: ' + record.type);
        console.log('Mutation target: ' + record.target);
    });
};var mo = new MutationObserver(callback);var option = {    
'childList': true,    'subtree': true};

mo.observer(document.body, option);
Copy after login

上面代码的观察器,观察body元素的所有下级元素(childList表示观察子元素,subtree表示观察子元素的下级元素)的变动。回调函数会在控制台显示所有变动的类型和目标元素。

3.2、属性的变动

下面的例子说明如何追踪属性的变动。

var callback = function(records) {
    records.map(function(record) {
        console.log('Previous attribute value: ' + record.oldValue);
    });
};
var mo = new MutationObserver(callback);
var element = document.getElementById('#my_element');
var option = {    
'attribute': true,    
'attributeOldValue': true};

mo.observer(element, option);
Copy after login

上面代码先设定追踪属性变动('attributes': true),然后设定记录变动前的值。实际发生变动时,会将变动前的值显示在控制台。

The above is the detailed content of Detailed explanation of HTML5 new features Mutation Observer code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template