考虑将事件处理程序标记为“被动"以使页面更具响应性 [英] Consider marking event handler as 'passive' to make the page more responsive

查看:37
本文介绍了考虑将事件处理程序标记为“被动"以使页面更具响应性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用锤子进行拖动,并且在加载其他内容时它变得断断续续,因为此警告消息告诉我.

I am using hammer for dragging and it is getting choppy when loading other stuff, as this warning message is telling me.

touchstart"输入事件的处理延迟了 X 毫秒,因为主线程忙.考虑将事件处理程序标记为被动"使页面更具响应性.

Handling of 'touchstart' input event was delayed for X ms due to main thread being busy. Consider marking event handler as 'passive' to make the page more responsive.

所以我试着像这样给听众添加被动"

So I tried to add 'passive' to the listener like so

Hammer(element[0]).on("touchstart", function(ev) {
  // stuff
}, {
  passive: true
});

但我仍然收到此警告.

推荐答案

对于那些第一次收到此警告的人来说,这是由于一个名为 Passive Event Listeners 的前沿功能已被实施最近在浏览器中(2016 年夏季).来自 https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md:

For those receiving this warning for the first time, it is due to a bleeding edge feature called Passive Event Listeners that has been implemented in browsers fairly recently (summer 2016). From https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md:

被动事件侦听器是 DOM 规范中的一项新功能,可启用开发人员可以通过消除需要滚动以阻止触摸和滚轮事件侦听器.开发人员可以使用 {passive: true} 注释触摸和滚轮侦听器表明他们永远不会调用 preventDefault.此功能在 Chrome 51、Firefox 49 中发布并在 WebKit 中登陆.有关完整的官方解释,请在此处阅读更多内容.

Passive event listeners are a new feature in the DOM spec that enable developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners. Developers can annotate touch and wheel listeners with {passive: true} to indicate that they will never invoke preventDefault. This feature shipped in Chrome 51, Firefox 49 and landed in WebKit. For full official explanation read more here.

另见:什么是被动事件监听器?

如果您通过 JavaScript 库间接处理事件,您可能会受制于该特定库对该功能的支持.截至 2019 年 12 月,似乎没有任何主要图书馆实施了支持.一些例子:

If you are handling events indirectly via a JavaScript library, you may be at the mercy of that particular library's support for the feature. As of December 2019, it does not look like any of the major libraries have implemented support. Some examples:

  • jQuery.js - ongoing issue: https://github.com/jquery/jquery/issues/2871
  • React.js - ongoing issue: https://github.com/facebook/react/issues/6436
  • Hammer.js - closed due to no follow up: https://github.com/hammerjs/hammer.js/pull/987
  • perfect-scrollbar - closed: https://github.com/noraesae/perfect-scrollbar/issues/560
  • AngularJS - closed due to won't fix: https://github.com/angular/angular.js/issues/15901

这篇关于考虑将事件处理程序标记为“被动"以使页面更具响应性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆