hevue-img-preview icon indicating copy to clipboard operation
hevue-img-preview copied to clipboard

使用 passive 优化 Event 滚动性能

Open lqzhgood opened this issue 3 years ago • 1 comments

我看到代码里面使用了很多 滚动Event,不使用默认行为的前提下 event.preventDefault() 可以使用 passive 来优化滚动性能。

Chrome 也会给出提示(我目前的版本是 97)。 [Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive. See https://www.chromestatus.com/feature/5745543795965952

对于 vue 来说,可以直接添加 .passive 修饰符,例如<div [@scroll.passive="onScroll">...</div>文档

原生来说可以使用 document.addEventListener('mousewheel', handler, {passive: true}) ,但是要注意兼容性。可以用这个库 https://github.com/zzarcon/default-passive-events

本来想直接改了 PR 的,但是代码中有很多疑问 https://github.com/heyongsheng/hevue-img-preview/blob/f812451e51ecf57035db756e8eec45472924256d/hevue-img-preview.vue#L207-L210

首先不建议使用 getElementById 去拿元素了,建议使用 vue 的 ref 拿到元素。并且建议直接在元素上通过 vue @mousewheel 直接绑定事件。这样 vue 会自动处理事件解绑,如果手动 addEventListener,建议在 vue 的 beforeDestroy 生命周期中 removeEventListener

这里是不是重复绑定了 onmousewheel DOMMouseScroll 事件? 建议 onmousewheel = fn 转化为 addEventListener 的方式添加,因为后者可以使用 {passive: true} 优化性能,onmousewheel = fn 我暂时不知道如何优化,如有有人知道请指教。

lqzhgood avatar Jan 30 '22 07:01 lqzhgood

感谢认真阅读源码并提出如此详细的优化方案,我会认真阅读并进行优化,祝你新年快乐

heyongsheng avatar Jan 30 '22 08:01 heyongsheng