【important! ! Use the passive optimize page performance

Add a listener to the event dom element in the js:

let dom1=document.getElementById("box1");
function box(that){
	console.log(that);
}
dom1.addEventListener("click",function(){box(1)});

General are like this, but there is still the third parameter, Boolean type. When set to true, the event capture state (execution events from outside inwards), false when status is bubbled up (event performed inside out), the default is false, since the use of event capture too.

But the third parameter may further object is, for example:

dom1.addEventListener("click",function(){box(1)},{
				passive:true,//告诉浏览器不用调用preventDefault(),可以执行默认行为
				capture:true,//事件捕获阶段,如果此元素的子元素被触发事件时,会先执行此事件
				once:true//此监听器只执行一次
				});

Key passive:

Tells the browser to execute the default behavior, this time there will be a question: "Default is not the default behavior is to perform it?"
Here Insert Picture Description
For example:

<style type="text/css">
			#box1{width: 400px;height: 1500px;background-color: antiquewhite;}
</style>

<body>
		<div id="box1"></div>
<script>
dom1.addEventListener("wheel",function(){
				let i=1;
				while(i++<1e15){
				}
				});	
</script>
</body>

If you try this page should collapse Austrian
Here Insert Picture Description
This page is the default behavior of the decline, though not prevent the default behavior, but the page is Xiabu Qu. Because the browser can not know in advance whether a listener calls the preventDefault (), it needs to wait for the listener after the implementation, go perform the default behavior, while the listener takes time function execution, the execution time is the time it waits (even if it is empty there will be a function of execution time). This will cause a page to decline Caton.
Plus try again:

dom1.addEventListener("wheel",function(){
				let i=1;
				while(i++<1e15){
				}
				},{
				passive:true
				});

Plus the passive = true browser will know, do not go calling preventDefault (), it will not wait any longer, silky straight vertical execute the default behavior.
This property in particular, attention needs to move very end.
Ha ha ha I think my simple and easy to understand, practical impressive
comparison point as well as the official video can be seen: here
also talked about the compatibility: here

Published 31 original articles · won praise 45 · views 5888

Guess you like

Origin blog.csdn.net/weixin_43623808/article/details/103403055