手写图片懒加载

//50ms节流方案
let lazyLoadThrottle = throttle(lazyLoad,50);
window.addEventListener('scroll',lazyLoadThrottle);

//raf的一帧节流方案
var isScroll = true;
window.addEventListener('scroll',function(){
    if(isScroll) return;
    requestAnimationFrame(lazyLoad);
})

function lazyLoad(opts){
    isScroll = true;
    let {conSel,imgSel,offset} = opts;
    let imgCon = document.querySelector(conSel);
    let rect = document.getBoundingClientRect();
    let clientH = document.documentElement.clientHeight;
    if(rect.top - clientH <= offset){
        let imgs = Array.from(imgCon.querySelector(imgSel));
        imgs.forEach(item => {
            let src = item.getAttribute('data-src');
            if(!src) return;
            item.src = src;
            item.removeAttribute('data-src');
        })
    }
}

function throttle(fn,interval){
    //last为0,cur必然大于它,fn会先立即执行一次
    let last = 0;
    return function(){
        let cur = +new Date();
        if(cur - last >= interval){
            fn.apply(this,args);
            last = cur;
        }
    }
}

 

posted @ 2020-05-11 23:42  全玉  阅读(278)  评论(0编辑  收藏  举报