美文网首页js
【web前端】passive是个啥?

【web前端】passive是个啥?

作者: 林哥学前端 | 来源:发表于2020-01-02 14:48 被阅读0次

    1.passive是个啥?

    passive是监听事件时候新增的一个选项
    以前js中监听事件是这样写的

    addEventListener(type, listener[, useCapture ])
    

    第一个参数是要监听的事件类型,第二个参数是事件的回调函数,第三个参数是是否允许事件捕获

    现在监听事件这样写

     addEventListener(type, listener, {
        capture: false, 
        passive: false, 
        once: false 
    })
    

    第三个参数变成了一个对象,有三个属性,
    第一个capture就是之前的useCapture,
    第二个passive就是咱们今天要说的主角

    2.passive有什么作用?

    passive就是为了改善移动端滚屏性能而设计的
    简单说就是如果你监听了window的scroll或者touchmove事件,你应该把passive设置为true,这样滚动就会流畅很多,像这样

    elem.addEventListener('touchmove', function listener() { /* do something */ }, { passive: true })
    

    3.passive的原理

    passive为false时,浏览器执行完回调函数才知道有没有调用preventDefault,如果没有调用preventDefault,再去执行默认行为,就是滚动。这样就回造成滚动不流畅。
    passive为true,就是告诉浏览器不会调用preventDefault,浏览器直接执行滚动就行,不用考虑回调函数了。
    这时,即使你在回调函数里调用preventDefault也不会生效。
    mdn中说,在有些浏览器(特别是Chrome和Firefox)中,你监听window、document或者document.body上的touchstart和touchmove,会将passive默认设置为true。
    还是要提醒大家,在你不需要调用preventDefault的时候,监听scroll或者touchmove,将passive设置为true

    相关文章

      网友评论

        本文标题:【web前端】passive是个啥?

        本文链接:https://www.haomeiwen.com/subject/hecooctx.html