最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What happens if I don't test Passive event listeners support? - Stack Overflow

programmeradmin5浏览0评论

Chromium gives me a warning about my event listener not being passive.

Fine.

I'm not going to use event.preventDefault() there so I am willing to make it passive.

But then when I read the detailed explanation, the example uses Modernizr to check if the attribute is available.

addEventListener(document, "touchstart", function(e) {
  }, Modernizr.passiveeventlisteners ? {passive: true} : false);

But I don't have Modernizr installed, and I find a pain to set it up for this very specific use case.

So the question is: what happens if I blindly write:

$el.addEventListener('touchstart', () => {}, {passive: true})?

in old browsers?

My guess is that the object might be evaluated to true, is that correct? No error to be risen?

Chromium gives me a warning about my event listener not being passive.

Fine.

I'm not going to use event.preventDefault() there so I am willing to make it passive.

But then when I read the detailed explanation, the example uses Modernizr to check if the attribute is available.

addEventListener(document, "touchstart", function(e) {
  }, Modernizr.passiveeventlisteners ? {passive: true} : false);

But I don't have Modernizr installed, and I find a pain to set it up for this very specific use case.

So the question is: what happens if I blindly write:

$el.addEventListener('touchstart', () => {}, {passive: true})?

in old browsers?

My guess is that the object might be evaluated to true, is that correct? No error to be risen?

Share Improve this question edited Mar 7, 2020 at 18:37 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 17, 2018 at 14:00 Augustin RiedingerAugustin Riedinger 22.3k32 gold badges146 silver badges219 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10 +50

{passive: true} will be evaluated as true so that should get rid of the Chromium warning, but according to the link you provided, it could have "unforseen results" on older browsers.

This method (also suggested in that link) seems pretty good to me, and it doesn't need any other libraries:

// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
  var opts = Object.defineProperty({}, 'passive', {
    get: function() {
      supportsPassive = true;
    }
  });
  window.addEventListener("testPassive", null, opts);
  window.removeEventListener("testPassive", null, opts);
} catch (e) {}

// Use our detect's results. passive applied if supported, capture will be false either way.
elem.addEventListener('touchstart', fn, supportsPassive ? { passive: true } : false);
发布评论

评论列表(0)

  1. 暂无评论