原生javascript-圖片滾動按需加載


圖片滾動按需加載:在某個區域的圖片(自定義的范圍,一般是首屏以下的區域),拉動滾動,圖片出現在可視范圍才開始加載,目的是減少請求,減耗寬帶,提高首屏的呈現速度,讓用戶第一時間看到網頁內容,留下美好的第一印象。

 

講解:

(一)需要按需加載的img標簽,圖片的真實地址保存到自定義的屬性里,如'data-src',那么src屬性用一張1像素透明的圖片

(二)把某范圍內的img標簽元素保存到數組里面

(三)定義一個方法:遍歷數組元素,然后判斷某元素的offsetTop是否在滾動的可視范圍,如果在,交換圖片的屬性('data-src','src'),然后刪除這個元素,那么在下次遍歷就不存在

 

load:function(){
        // 全部加裝,解除事件
        if(this.imgList.length == 0){
            this.removeHandler(window,'scroll',this.fnLoad);
            this.removeHandler(window,'resize',this.fnLoad);
            return
        }
        var st = document.body.scrollTop || document.documentElement.scrollTop,
            clientH = document.documentElement.clientHeight,
            scrollArea = st + clientH;
        for(var n=0;n<this.imgList.length;n++){
            var offsetTop = this.imgList[n].getBoundingClientRect().top+st,
                imgH = this.imgList[n].clientHeight;
            if( scrollArea>(offsetTop-200)&&(imgH+offsetTop)>st ){
                var _src = this.imgList[n].getAttribute(this.holderSrc);
                this.imgList[n].setAttribute('src',_src);                
                this.imgList.splice(n,1);//刪除已經加載完的元素
                n--;
            }
        }

 }

 

(四)給window對象,scroll與resize 添加此事件

(五)用戶有可能快速拉滾動條,這樣會導致事件的頻繁觸發,所以需要添加個setTimeout

bind:function(obj,fn){
        var _this = this;
        return function(){
            if(_this.timer) clearTimeout(_this.timer);
            _this.timer = setTimeout(function(){
                fn.apply(obj,arguments);
            },300);
            
        }
}

 

完整代碼:

function LazyScroll(opt){
    this.init(opt);
}
LazyScroll.prototype = {
    init:function(opt){
        this.setOptions(opt);
        this.load();
        this.fnLoad = this.bind(this,this.load);
        this.addHandler(window,'scroll',this.fnLoad);
        this.addHandler(window,'resize',this.fnLoad);
    },
    setOptions:function(opt){
        this.holderSrc = opt.holderSrc || 'data-src';
        this.wrapId = opt.wrapId;
        this.imgList = [];
        this.timer = null;
        var targets = null;
        if (document.querySelectorAll) {
            targets = document.querySelectorAll("#" + this.wrapId + " img")
        } else {
            targets = document.getElementById(this.wrapId).getElementsByTagName("img")
        }
        var n = 0,
            len = targets.length;
        // 把元素存到數組里
        for(;n<len;n++){
            if(targets[n].getAttribute(this.holderSrc)){
                this.imgList.push(targets[n]);
            }
        }
    },
    load:function(){
        // 全部加裝,解除事件
        if(this.imgList.length == 0){
            this.removeHandler(window,'scroll',this.fnLoad);
            this.removeHandler(window,'resize',this.fnLoad);
            return
        }
        var st = document.body.scrollTop || document.documentElement.scrollTop,
            clientH = document.documentElement.clientHeight,
            scrollArea = st + clientH;
        for(var n=0;n<this.imgList.length;n++){
            var offsetTop = this.imgList[n].getBoundingClientRect().top+st,
                imgH = this.imgList[n].clientHeight;
            if( scrollArea>(offsetTop-200)&&(imgH+offsetTop)>st ){
                var _src = this.imgList[n].getAttribute(this.holderSrc);
                this.imgList[n].setAttribute('src',_src);                
                this.imgList.splice(n,1);//刪除已經加載完的元素
                n--;
            }
        }

    },
    bind:function(obj,fn){
        var _this = this;
        return function(){
            if(_this.timer) clearTimeout(_this.timer);
            _this.timer = setTimeout(function(){
                fn.apply(obj,arguments);
            },300);
            
        }
    },
    addHandler:function(node,type,fn){
        if(node.addEventListener){
            node.addEventListener(type,fn,false);  
        }
        else{
            node.attachEvent('on'+type,function(){
                fn.apply(node,arguments); 
            });
        }
    },
    removeHandler: function(node, type, fn) {
        if (node.addEventListener) {
            node.removeEventListener(type, fn, false);
        } else {
            node.detachEvent("on" + type, fn);
        }
    }
}

 

<body id="body">
    <img src="xxxx" width="990" height="90" data-src="http://dummyimage.com/990x90/333/fff" alt="">
    <img src="xxxx" width="990" height="90" data-src="http://dummyimage.com/990x90/f60/fff" alt="">
    <img src="xxxx" width="990" height="90" data-src="http://dummyimage.com/990x90/259/fff" alt="">
    <img src="xxxx" width="990" height="90" data-src="http://dummyimage.com/990x90/999/fff" alt="">
    <img src="xxxx" width="990" height="90" data-src="http://dummyimage.com/990x90/4D3434/fff" alt="">
    <img src="xxxx" width="990" height="90" data-src="http://dummyimage.com/990x90/344D3C/fff" alt="">
    <script type="text/javascript" src="scrollLazy.js"></script>
    <script type="text/javascript">
        new LazyScroll({'wrapId':'body'});
    </script>
</body>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM