且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

警告:添加非被动事件侦听器到滚动阻塞'touchstart'事件

更新时间:2022-10-14 18:40:45

有一个事件监听器API的更新。



简而言之:

  document.addEventListener('touchstart',handler,true); 

变成这样:

  document.addEventListener('touchstart',handler,{capture:true}); 

因为在您的情况下,您将触发器的事件监听器附加到它应该是这样的:

  document.addEventListener('touchstart',handler,{passive:true}); 

通过这种方式,您可以事先设置确切的事件以及被动接口是否被支持:

  var passiveEvent = false; 
var opts = Object.defineProperty({},'passive',{
get:function(){
passiveEvent = true;
}
});
window.addEventListener(test,null,opts);
} catch(e){}

//在我的情况下,我需要将passive和capture都设置为true,根据需要进行更改。
passiveEvent = passiveEvent? {capture:true,passive:true}:true;

//如果您需要在HTMLDivElement.prototype中处理鼠标滚轮
var supportedWheelEvent:string =onwheel? wheel:
document.onmousewheel!== undefined? mousewheel:DOMMouseScroll;

并且像这样使用:

  elementRef.addEventListener(touchstart,handler,passiveEvent); 

有关被动事件侦听器的更多详细信息:
https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md

I am getting a weird warning while opening the application in chrome.I don't know how to get rid of this warning

[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.

any one pls help me put on this.Thanks in advance

There is an update of the API of event listeners.

In short this:

document.addEventListener('touchstart', handler, true);

becomes this:

document.addEventListener('touchstart', handler, {capture: true});

Since in your case you attach event listener to touchstart it should be like that:

document.addEventListener('touchstart', handler, {passive: true});

This way you can setup in advance which exact event and if the passive interface is supported:

var passiveEvent = false;
try {
    var opts = Object.defineProperty({}, 'passive', {
        get: function () {
            passiveEvent = true;
        }
    });
    window.addEventListener("test", null, opts);
} catch (e) { }

// in my case I need both passive and capture set to true, change as you need it.
    passiveEvent = passiveEvent ? { capture: true, passive: true } : true;

//if you need to handle mouse wheel scroll
var supportedWheelEvent: string = "onwheel" in HTMLDivElement.prototype ? "wheel" :
    document.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll";

And use like this:

elementRef.addEventListener("touchstart", handler, passiveEvent);

More details on passive event listeners here: https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md