移动端 touch 性能问题及 passive

这种问题大部分是因为出像这样的错误:
Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080

原因

  • 浏览器需要在执行完事件处理后,才能获取是否用掉了preventDefault(),这就导致浏览器不能及时滚动
  • 即手滑动时,会有凝滞的问题,因此,从chrome56起,window, document, body上注册的touchstart, touchmove等事件处理函数
  • 默认为:passive:true,即忽略preventDefault(),这样就能顺滑滚动;
  • 因此,当你使用了 preventDefault(),就会报以上那样的错误。

解决方案

// 0.
window.addEventListener('touchmove', func, {passive: false})
// 1.
touch-action: none;

解决方案2

  • 如果你是有可能在多个绑定方法内使用 event.preventDefault(),而非只在touch事件下使用,那么
  • 可以对事件进行一些判断
window.addEventListener(eventName,  evt => {
  if (evt.cancelable) {         // 该事件可否被禁用
    if (!evt.defaultPrevented){ // 该事件是否已经被禁用
      evt.preventDefault()
    }
  }
}, {passive: false})

results matching ""

    No results matching ""