当前位置:网站首页>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
边栏推荐
- Pat class a 1150 traveling salesman problem
- Access数据库引入datagridview数据后,显示错误
- CFdiv1+2-Bash and a Tough Math Puzzle-(线段树单点区间维护gcd+总结)
- Log4qt memory leak, use of heob memory detection tool
- 性能更佳、使用更简单的懒加载IntersectionObserverEntry(观察者)
- 【FPGA教程案例42】图像案例2——通过verilog实现图像二值化处理,通过MATLAB进行辅助验证
- [MySQL] - [subquery]
- 工业互联网行至深水区,落地的路要怎么走?
- MySQL uses date_ FORMAT(date,'%Y-%m')
- Output 1234 three digits without repetition
猜你喜欢
功能自动化测试实施的原则以及方法有哪些?

Halcon installation and testing in vs2017, DLL configuration in vs2017

I, 28, a tester, was ruthlessly dismissed in October: I want to remind people who are still learning to test
![[untitled] format save](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[untitled] format save

SEGGER 的硬件异常 分析

零数科技深度参与信通院隐私计算金融场景标准制定

Amazon cloud assistant applet is coming!

Meeting notice of OA project (Query & whether to attend the meeting & feedback details)

Cs61abc sharing session (VI) detailed explanation of program input and output - standard input and output, file, device, EOF, command line parameters
What are the common error types and solutions of black box testing?
随机推荐
关于大龄读博的几点回答?
zip gzip tar压缩进阶版
PAT甲级 1154 顶点着色
log4qt内存泄露问题,heob内存检测工具的使用
Credit card shopping points
【暑期每日一题】洛谷 P1601 A+B Problem(高精)
[summer daily question] Luogu p4414 [coci2006-2007 2] ABC
[WPF] realize language switching through dynamic / static resources
在js中,0表示false,非0表示true
Meizhi optoelectronics' IPO was terminated: annual revenue of 926million he Xiangjian was the actual controller
Prometheus与Grafana
Amazon cloud assistant applet is coming!
mysql 使用 DATE_FORMAT(date,'%Y-%m')
Can the subset of the array accumulate K
Log4qt memory leak, use of heob memory detection tool
halcon的安装以及在vs2017中测试,vs2017中dll的配置
The difference between static library and dynamic library of program
电子元器件贸易企业如何借助ERP系统,解决仓库管理难题?
功能自动化测试实施的原则以及方法有哪些?
Docker's latest super detailed tutorial - docker creates, runs, and mounts MySQL