Javascript 什么是被动事件侦听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37721782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:40:23  来源:igfitidea点击:

What are passive event listeners?

javascriptdom-eventsevent-listenerpassive-event-listeners

提问by Vivek Pratap Singh

While working around to boost performance for progressive web apps, I came across a new feature Passive Event Listenersand I find it hard to understand the concept.

在努力提高渐进式 Web 应用程序的性能时,我遇到了一个新功能Passive Event Listeners,我发现很难理解这个概念。

What are Passive Event Listenersand what is the need to have it in our projects?

Passive Event Listeners在我们的项目中是什么以及需要什么?

回答by Vivek Pratap Singh

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

被动事件侦听器是一项新兴的 Web 标准,是 Chrome 51 中附带的新功能,可为滚动性能提供重大的潜在提升。Chrome 发行说明。

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

它使开发人员能够通过消除滚动来阻止触摸和滚轮事件侦听器来选择加入以获得更好的滚动性能。

Problem:All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstartand touchmovehandlers, which may prevent the scroll entirely by calling preventDefault()on the event.

问题:所有现代浏览器都有一个线程滚动特性,即使在运行昂贵的 JavaScript 时也允许滚动平滑运行,但是这种优化部分被等待 anytouchstarttouchmove处理程序的结果的需要打败了,这可能会通过调用完全阻止滚动preventDefault()在活动上。

Solution: {passive: true}

解决方案: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefaultto disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

通过将触摸或滚轮侦听器标记为被动,开发人员承诺处理程序不会调用preventDefault禁用滚动。This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec, Demo Video, Explainer Doc

DOM 规范演示视频说明文档