jackieli123723 / jackieli123723.github.io

✅lilidong 个人博客
9 stars 0 forks source link

window.addEventListener 使用 passive 改善的滚屏性能 #73

Open jackieli123723 opened 5 years ago

jackieli123723 commented 5 years ago

window.addEventListener 使用 passive 改善的滚屏性能

使用 passive 改善的滚屏性能节

根据规范,passive 选项的默认值始终为false。但是,这引入了处理某些触摸事件(以及其他)的事件监听器在尝试处理滚动时阻止浏览器的主线程的可能性,从而导致滚动处理期间性能可能大大降低。

为防止出现此问题,某些浏览器(特别是Chrome和Firefox)已将touchstart和touchmove事件的passive选项的默认值更改为true文档级节点 Window,Document和Document.body。这可以防止调用事件监听器,因此在用户滚动时无法阻止页面呈现。

var elem = document.getElementById('elem'); elem.addEventListener('touchmove', function listener() { / do something / }, { passive: true }); 添加passive参数后,touchmove事件不会阻塞页面的滚动(同样适用于鼠标的滚轮事件)。在这里查看

demo(需要翻墙)

 window.addEventListener('scroll', update, {passive: true})