scroll优化之防抖与节流

这个优化方案是参照 【前端性能】高性能滚动 scroll 及页面渲染优化html

在这里简单的把两个方式写出来,以便快速了解。。前端

第一种:防抖(也就是滚动结束才执行)闭包

演示:
图片描述dom

闭包:前端性能

/*
    延时执行
    @param fn function
    @param wait number
    @return function
*/
function debounce(fn, wait) {
    var timeout = null;
    return function() {
        if(timeout !== null) clearTimeout(timeout);
        timeout = setTimeout(fn, wait);
    }
}
// 处理函数
function handle() {
    console.log(Math.random()); 
}
// 滚动事件
window.addEventListener('scroll', debounce(handle, 500));

直接写:函数

var timeout = null;
window.addEventListener('scroll', function() {
    if(timeout !== null) clearTimeout(timeout);
    timeout = setTimeout(function() {
        var scrollTop = this.scrollY;
        console.log(scrollTop);
    }.bind(this), 500);
});

第二个是节流(Throttling)滚动的过程当中间隔执行,例如滚动加载图片效果,不可能等到滚动结束才执行加载函数数吧,因此这里能够作一个间隔执行。。性能

演示:
图片描述优化

闭包:this

/*
    节流函数
    @param fn function
    @param wait number
    @param maxTimeLong number
    @return function
*/
function throttling(fn, wait, maxTimelong) {
    var timeout = null,
        startTime = Date.parse(new Date);

    return function() {
        if(timeout !== null) clearTimeout(timeout);
        var curTime = Date.parse(new Date);
        if(curTime-startTime>=maxTimelong) {
            fn();
            startTime = curTime;
        } else {
            timeout = setTimeout(fn, wait);
        }
    }
}

function handle() {
    console.log(Math.random()); 
}

window.addEventListener('scroll', throttling(handle, 300, 1000));

直接写:spa

var timeout = null,
    startTime = Date.parse(new Date); // 开始时间

function handle() {
    console.log(Math.random()); 
}

window.addEventListener('scroll', function() {
    if(timeout !== null) clearTimeout(timeout);
    var curTime = Date.parse(new Date); // 当前时间
    if(curTime-startTime>=1000) { // 时间差>=1秒直接执行
        handle();
        startTime = curTime;
    } else { // 不然延时执行,像滚动了一下,差值<1秒的那种也要执行
        timeout = setTimeout(handle, 300);
    }
});

诸如此类事件的还有resize事件均可以使用这两种方式,固然使用哪种,还要看项目需求了。。谢谢关注~

相关文章
相关标签/搜索