javascript:Mutation Observer API

Original sentence: Https://Wangdoc.Com/javascript/index.Html

Mutation Observer API

Outline

Mutation Observer API used to monitor changes in DOM. DOM of any changes, such as changes in the node, change attributes, change text content, this API can be notified.

Conceptually, it is very close to the event, it can be understood as DOM Mutation Observer changed will trigger event. However, it is essentially a different event: the event is synchronized trigger, that is to say, DOM changes will immediately trigger the corresponding event; Mutation Observer is triggered asynchronously, DOM changes will not trigger immediately, but to wait until the current All DOM operations before the end of the trigger.

This is designed to cope with frequent changes in DOM features. For example, if the document is inserted in consecutive 1000 <p>elements, will trigger 1000 consecutive insertion event, callback function for each event, which is likely to cause the browser Caton; and Mutation Observer completely different, only in 1000 paragraph is inserted after the end will trigger, and the trigger only once.

Mutation Observer has the following characteristics.

  • It waits for all scripts after the task is completed, will run (ie asynchronous trigger mode).
  • It DOM change recording processing package into an array, rather than an individual section changes the DOM.
  • It can be observed in all types of changes in the DOM, you can specify only observe a certain type of change.

MutationObserver Constructor

In use, the use of MutationObservera constructor, a new instance of a viewer, while this example specify a callback function.

var observer = new MutationObserver(callback);

The above code callback function will be called after each change in DOM. The callback function accepts two arguments, the first is a change in an array, the second instance is observed, the following is an example.

var observer = new MutationObserver(function (mutations, observer) {
  mutations.forEach(function(mutation) {
    console.log(mutation);
  });
});

Examples of methods MutationObserver

observe()

observeThe method used to start the listener, it takes two arguments.

  • DOM node to be observed: the first parameter
  • The second parameter: a configuration object, specify the specific variation to be observed
var article = document.querySelector('article');

var  options = {
  'childList': true,
  'attributes':true
} ;

observer.observe(article, options);

The above code, the observemethod takes two parameters, a first DOM element is to be observed that article, the second type of change is to be observed (the property change and changes in the child node).

DOM change type observer can observe (i.e. above code optionsobjects), there are several.

  • childList : changes in child nodes (refer to add, delete or change).
  • the Attributes : changes in the property.
  • characterData : changes in content or node node text.

Which type of change you want to observe, in optionthe specified value of its object true. Note that you must specify the same time childList, attributesand characterDatain one or more of, if not all specify an error.

In addition to changes in the type of optionsobject you can also set the following properties:

  • subtree: Boolean value that indicates whether the viewer is applied to all descendant nodes of the node.
  • attributeOldValue: Boolean value that indicates observe attributeswhen changes need to record whether the property value before the change.
  • characterDataOldValue: Boolean value that indicates observe characterDatawhen changes need to record the value before the change.
  • attributeFilter: Array representing specific attributes (such as the need of observation ['class','src']).
// 开始监听文档根节点(即<html>标签)的变动
mutationObserver.observe(document.documentElement, {
  attributes: true,
  characterData: true,
  childList: true,
  subtree: true,
  attributeOldValue: true,
  characterDataOldValue: true
});

To add a node observer, just like addEventListenerthe same way as, repeatedly add the same observation is invalid, the callback function is still only trigger once. If you specify a different optionsobject to that subject later added similar coverage.

The following example is a new observation of the child node.

var insertedNodes = [];
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    for (var i = 0; i < mutation.addedNodes.length; i++) {
      insertedNodes.push(mutation.addedNodes[i]);
    }
  });
  console.log(insertedNodes);
});
observer.observe(document, { childList: true, subtree: true });

disconnect(),takeRecords()

disconnectThe method used to stop watching. After calling this method, DOM change happen again, it will not trigger the viewer.

observer.disconnect();

takeRecordsThe method of recording changes to clear, i.e., no change in the untreated process. This method returns an array of changes in records.

observer.takeRecords();

Below is an example.

// 保存所有没有被观察器处理的变动
var changes = mutationObserver.takeRecords();

// 停止观察
mutationObserver.disconnect();

MutationRecord objects

DOM changes each time, a change record is generated (MutationRecord instance). This example contains all the information related to the change. Mutation Observer process is one of MutationRecordan array composed of examples.

MutationRecordDOM object contains information of the following properties:

  • type: Observation of changes in the type attributes( , characterDataor childList).
  • target: DOM node fluctuates.
  • addedNodes: New DOM node.
  • removedNodes: Delete DOM node.
  • previousSibling: Previous sibling node, if there is no return null.
  • nextSibling: Next sibling node, if there is no return null.
  • attributeName: Property changes occur. If set attributeFilter, returns only pre-specified properties.
  • oldValue: The value before the change. This property only attributeand characterDatachanges effective, if the occurrence of childListchange is returned null.

Application Examples

Changes in the child element

The following example shows how to read change records.

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.observe(document.body, option);

The above code viewer to observe <body>all lower nodes ( childListrepresented observed child node subtreechanges observed indicates descendant node). The callback function will display all types and target nodes changes in the console.

Changes in property

The following example shows how to track changes in property.

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 options = {
  'attributes': true,
  'attributeOldValue': true
}

mo.observe(element, options);

The above attribute change tracking code is previously set ( 'attributes': true), and then changes the set value before recording. When the actual change occurs, the value before the change will be displayed on the console.

Replace DOMContentLoaded event

When the page loads, generate DOM nodes will produce change history, so long as the observed changes in the DOM, you can trigger the relevant event for the first time, there is no need to use DOMContentLoadedevents.

var observer = new MutationObserver(callback);
observer.observe(document.documentElement, {
  childList: true,
  subtree: true
});

The above code, the listener document.documentElement(i.e., the page <html>change HTML nodes) of the child node subtreeattribute specifies the node listens further include progeny. Thus, any element of a web page Once generated, it can immediately listen to.

The following code, using the MutationObserverobject encapsulates a function generated DOM listener.

(function(win){
  'use strict';

  var listeners = [];
  var doc = win.document;
  var MutationObserver = win.MutationObserver || win.WebKitMutationObserver;
  var observer;

  function ready(selector, fn){
    // 储存选择器和回调函数
    listeners.push({
      selector: selector,
      fn: fn
    });
    if(!observer){
      // 监听document变化
      observer = new MutationObserver(check);
      observer.observe(doc.documentElement, {
        childList: true,
        subtree: true
      });
    }
    // 检查该节点是否已经在DOM中
    check();
  }

  function check(){
  // 检查是否匹配已储存的节点
    for(var i = 0; i < listeners.length; i++){
      var listener = listeners[i];
      // 检查指定节点是否有匹配
      var elements = doc.querySelectorAll(listener.selector);
      for(var j = 0; j < elements.length; j++){
        var element = elements[j];
        // 确保回调函数只会对该元素调用一次
        if(!element.ready){
          element.ready = true;
          // 对该节点调用回调函数
          listener.fn.call(element, element);
        }
      }
    }
  }

  // 对外暴露ready
  win.ready = ready;

})(this);

// 使用方法
ready('.foo', function(element){
  // ...
});

Reference links

Guess you like

Origin www.cnblogs.com/wbyixx/p/12499266.html