Table of Contents
1. Overview
2. Usage method
2.1 observer method
2.2 disconnect method and takeRecord method
2.3 MutationRecord object
3、实例
3.1 子元素的变动
3.2、属性的变动
Home Web Front-end H5 Tutorial Detailed explanation of HTML5 new features Mutation Observer code

Detailed explanation of HTML5 new features Mutation Observer code

Mar 30, 2017 am 11:29 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles