当前位置:网站首页>Mutationobserver document learning
Mutationobserver document learning
2022-07-29 07:42:00 【Pontoon bridge】
1. summary
Mutation Observer API Used to monitor DOM change .DOM Any changes , Let's say I add or subtract nodes 、 Change of attribute 、 Changes in text content , This API Both can be notified .
Conceptually , It's very close to the event , It can be understood as DOM It's triggered by a change Mutation Observer event . however , It has an essential difference from events : Events are triggered synchronously , in other words ,DOM Immediately triggers the corresponding event ;Mutation Observer It is triggered asynchronously ,DOM The change will not be triggered immediately , Instead, wait until it's all there DOM This is triggered after all operations are completed .
This is designed to cope DOM A characteristic of frequent change . for instance , If the document is inserted continuously 1000 individual
Elements , It will trigger continuously 1000 Two insert events , Executes the callback function for each event , This is likely to cause the browser to jam ; and Mutation Observer Completely different , Only in 1000 It will not be triggered until all paragraphs have been inserted , And it only happens once .
Mutation Observer Has the following characteristics :
- It waits for all the script tasks to complete , Will run ( Asynchronous trigger mode ).
- It is the DOM The change records are encapsulated in an array for processing , Not one by one DOM change .
- It can both observe DOM All types of changes , You can also specify that only one type of change be observed .
2. MutationObserver Constructors
When using , use first MutationObserver Constructors , Create a new observer instance , Also specify the callback function of this instance . Callback function , Every time DOM After changing, call . The callback function takes two parameters , The first is the variable array , The second is the observer instance
var observer = new MutationObserver(function (mutations, observer) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
});
3. MutationObserver Instance method of
1. observe()
observe Method to start a listener , It takes two arguments . The first is to observe DOM The element is article, The second is the type of change to be observed ( Sub node change and attribute change ).
The first parameter : To observe DOM node
The second parameter : A configuration object , Specify the specific changes to be observed
var article = document.querySelector('article');
var options = {
'childList': true,
'attributes':true
} ;
observer.observe(article, options);
(1) What the observer can observe DOM Change type ( That's the code above options object ), Yes :
childList: Changes in child nodes ( Refers to new , Delete or change ).
attributes: Change of attribute .
characterData: Changes in node content or node text .
What type of change do you want to observe , It's just option Object specifies that its value is true. It should be noted that , Must specify at the same time childList、attributes and characterData One or more of , If not specified, an error will be reported .
(2) Except for the type of change ,options Object can also set the following properties :
subtree: Boolean value , Indicates whether the observer is applied to all descendant nodes of the node .
attributeOldValue: Boolean value , To observe attributes When changing , Whether it is necessary to record the attribute value before the change .
characterDataOldValue: Boolean value , To observe characterData When changing , Is it necessary to record the value before the change .
attributeFilter: Array , Represents a specific attribute that needs to be observed ( such as [‘class’,‘src’]).
// Start listening to the document root node ( namely <html> label ) The change of
mutationObserver.observe(document.documentElement, {
attributes: true,
characterData: true,
childList: true,
subtree: true,
attributeOldValue: true,
characterDataOldValue: true
});
Add an observer to a node , It's like using addEventListener The method is the same , Adding the same observer more than once is invalid , The callback function will still trigger only once . however , If you specify a different options object , Will be treated as two different observers .
2. disconnect(),takeRecords()
(1) disconnect Method to stop observation . After calling this method ,DOM Another change , And it doesn't trigger the viewer .
observer.disconnect();
(2) takeRecords Method to clear change records , That is, it no longer deals with unprocessed changes . This method returns an array of change records .
observer.takeRecords();
4. MutationRecord object
DOM Every time it changes , A change record will be generated (MutationRecord example ). This example contains all the information about the change .Mutation Observer What we deal with is one by one MutationRecord The array of instances .
MutationRecord The object contains DOM Information about , Has the following properties :
type: Types of changes observed (attribute、characterData perhaps childList).
target: fluctuating DOM node .
addedNodes: Newly added DOM node .
removedNodes: Delete the DOM node .
previousSibling: The previous sibling node , If not, return null.
nextSibling: Next sibling node , If not, return null.
attributeName: A property that has changed . If set attributeFilter, Returns only the previously specified properties .
oldValue: The value before the change . This property is only true attribute and characterData Changes in the effective , In case of childList change , Then return to null.
5. Application example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MutationObserver Constructors </title>
<style> ul {
width: 510px; padding: 10px; border: 1px solid #ccc; } li {
width: 500px; height: 60px; list-style-type: none; line-height: 60px; margin-bottom: 10px; font-size: 36px; color: #535353; border: 1px solid rgb(245, 156, 156); } </style>
</head>
<body>
<div>
<button onclick="stopObserving()"> Stop observing </button>
</div>
<ul class="article1">
<li class="list1">1</li>
<li class="list1">2</li>
<li class="list1">3</li>
</ul>
<div>
<button onclick="childChange()"> The change of subelements </button>
<button onclick="openObserving(1)"> Open observation </button>
</div>
<ul class="article2">
<li class="list2">1</li>
<li class="list2">2</li>
<li class="list2">3</li>
</ul>
<div>
<button onclick="propertiesChange()"> Change of attribute </button>
<button onclick="openObserving(2)"> Open observation </button>
</div>
<script type="text/javaScript"> var article = document.querySelector(".article1") var article2 = document.querySelector(".article2") var timer = null function childChange(){
console.log(' The change of subelements ') var lis = document.getElementsByClassName('list1') if(!lis.length){
for(let i=0;i<6;i++){
timer = setTimeout(() => {
var li = document.createElement('li'); li.innerHTML = i + 1 article.appendChild(li); }, 1000*(i+1)); } }else{
for(let i=0;i<lis.length;i++){
timer = setTimeout(() => {
console.log(' Variable subscript :',i) article.removeChild(lis[0]) }, 1000*(i+1)); } } // var li1 = lis[0] // // Delete the first child node // ul.removeChild(li1) } function propertiesChange(){
console.log(' Change of attribute ') // clientWidth: Gets the width of the visible part of the element , namely CSS Of width and padding The sum of attribute values , Element borders and scroll bars are not included , It also does not contain any possible scrolling areas // console.log(article2.clientWidth); if(article2.clientWidth === 530){
article2.style.width = '700px' }else{
article2.style.width = '510px' } } /** 1. MutationObserver Constructor uses * Use MutationObserver Constructors , Create a new observer instance , Also specify the callback function of this instance . * Callback function , Every time DOM After changing, call . The callback function takes two parameters , The first is the variable array , The second is the observer instance . */ var callback = function (mutations, observer) {
console.log(' monitor ',mutations, observer) mutations.map(function(record){
// The change of subelements console.log('Mutation type: ' + record.type); console.log('Mutation target: ' + record.target); // Change of attribute console.log('Previous attribute value: ' + record.oldValue); /** Change records : MutationRecord object ( And mutations object ) * DOM Every time it changes , A change record will be generated (MutationRecord example ). This example contains all the information about the change .Mutation Observer What we deal with is one by one MutationRecord The array of instances . * * MutationRecord Object contains DOM Information about : * (1). type: Types of changes observed (attribute、characterData perhaps childList). * (2). target: fluctuating DOM node . * (3). addedNodes: Newly added DOM node . * (4). removedNodes: Delete the DOM node . * (5). previousSibling: The previous sibling node , If not, return null. * (6). nextSibling: Next sibling node , If not, return null. * (7). attributeName: A property that has changed . If set attributeFilter, Returns only the previously specified properties . * (8). oldValue: The value before the change . This property is only true attribute and characterData Changes in the effective , In case of childList change , Then return to null. */ }); } var observer = new MutationObserver(callback) /** 2. MutationObserver Instance method of * observe Method to start a listener , It takes two arguments .( The first parameter : To observe DOM node , The second parameter : A configuration object , Specify the specific changes to be observed ) * * Configuration object : * (1) childList: Changes in child nodes ( Refers to new , Delete or change ). * (2) attributes: Change of attribute . * (3) characterData: Changes in node content or node text . * (4) subtree: Boolean value , Indicates whether the observer is applied to all descendant nodes of the node . * (5) attributeOldValue: Boolean value , To observe attributes When changing , Whether it is necessary to record the attribute value before the change . * (6) characterDataOldValue: Boolean value , To observe characterData When changing , Is it necessary to record the value before the change . * (7) attributeFilter: Array , Represents a specific attribute that needs to be observed ( such as ['class','src']). */ // notes : Must specify at the same time childList、attributes and characterData One or more of , If not specified, an error will be reported . // console.log("article", article,article2) // Change configuration of child elements var options = {
'attributes': true, 'childList': true, 'subtree': true } // Change configuration of attributes var options2 = {
'attributes': true, 'attributeOldValue': true, } observer.observe(article, options) observer.observe(article2, options2) function stopObserving(params) {
/** disconnect(): * disconnect Method to stop observation . After calling this method ,DOM Another change , And it doesn't trigger the viewer . */ console.log(' Stop observing ') observer.disconnect(); /** takeRecords(): * takeRecords Method to clear change records , That is, it no longer deals with unprocessed changes . This method returns an array of change records . */ // Save all changes that have not been processed by the observer var changes = observer.takeRecords(); console.log(' Changes that are not handled by the observer ',changes) } function openObserving(params) {
if(params===1){
console.log(' Open the observation of the changes of child elements ') observer.observe(article, options) }else{
console.log(' Open attribute change observation ') observer.observe(article2, options2) } } </script>
</body>
</html>


- The results of the execution show that
disconnect()Method will stop all observation , Elements that need to be observed after execution need to be re opened for observation
边栏推荐
- flutter只要是数据,都会判空的
- [daily question in summer] Luogu p6408 [coci2008-2009 3] pet
- jdbc入门
- 梳理市面上的2大NFT定价范式和4种解决方案
- 10 practical uses of NFT
- String类
- Analyze the roadmap of 25 major DFI protocols and predict the seven major trends in the future of DFI
- Description of rollingfileappender attribute in logback
- Can the subset of the array accumulate K
- QT连接两个qslite数据库报错QSqlQuery::exec: database not open
猜你喜欢

What are the answers about older bloggers?
功能自动化测试实施的原则以及方法有哪些?

STM32 operation w25q256 w25q16 SPI flash

Getting started with JDBC

Segger's hardware anomaly analysis
![【暑期每日一题】洛谷 P6461 [COCI2006-2007#5] TRIK](/img/bf/c0e03f1bf477730f0b3661b3256d1d.png)
【暑期每日一题】洛谷 P6461 [COCI2006-2007#5] TRIK

Technology sharing | quick intercom integrated dispatching system

Can the subset of the array accumulate K

分析25个主要DeFi协议的路线图 预见DeFi未来的七大趋势
![[untitled] format save](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[untitled] format save
随机推荐
The new generation of public chain attacks the "Impossible Triangle"
[daily question in summer] Luogu p6408 [coci2008-2009 3] pet
Technology sharing | quick intercom integrated dispatching system
CFdiv1+2-Bash and a Tough Math Puzzle-(线段树单点区间维护gcd+总结)
状态机dp(简单版)
IonIcons图标大全
Docker's latest super detailed tutorial - docker creates, runs, and mounts MySQL
mysql 使用 DATE_FORMAT(date,'%Y-%m')
Using C language to skillfully realize the chess game -- Sanzi chess
Sort out the two NFT pricing paradigms and four solutions on the market
gin abort不能阻止后续代码的问题
RoBERTa:A Robustly Optimized BERT Pretraining Approach
Better performance and simpler lazy loading of intersectionobserverentry (observer)
Pat class a 1150 traveling salesman problem
flutter只要是数据,都会判空的
Monitor the bottom button of page scrolling position positioning (including the solution that page initialization positioning does not take effect on mouse sliding)
The beauty of do end usage
【无标题】格式保存
[summer daily question] Luogu p6461 [coci2006-2007 5] trik
小D的刺绣