图片懒加载

图片懒加载

在实际的项目开发中,我们经常遇到这样的情况:一个页面要展示的图片很多,但是在首屏出现的图片只有几张。如果我们一次性把所有的图片都加载出来,会影响页面的渲染速度,还浪费带宽。我们需要做的就是把首屏的图片先展示,不可视区域的图片不展示,等图片到达可视区域的时候再加载,这就是我们图片懒加载。

思路:

将页面里所有img属性src属性用data-xx代替,当页面滚动直至此图片出现在可视区域时,用js取到该图片的data-xx的值赋给src,同时移除data-xxx属性。

懒加载判断条件如下图所示
js懒加载图片.png

html结构

 ![](http://upload-images.jianshu.io/upload_images/3453618-e31c0108123ec0b7.gif?imageMogr2/auto-orient/strip) 

  1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
![](http://upload-images.jianshu.io/upload_images/3453618-e31c0108123ec0b7.gif?imageMogr2/auto-orient/strip)
![](http://upload-images.jianshu.io/upload_images/3453618-e31c0108123ec0b7.gif?imageMogr2/auto-orient/strip)
![](http://upload-images.jianshu.io/upload_images/3453618-e31c0108123ec0b7.gif?imageMogr2/auto-orient/strip)
![](http://upload-images.jianshu.io/upload_images/3453618-e31c0108123ec0b7.gif?imageMogr2/auto-orient/strip)
![](http://upload-images.jianshu.io/upload_images/3453618-e31c0108123ec0b7.gif?imageMogr2/auto-orient/strip)
![](http://upload-images.jianshu.io/upload_images/3453618-e31c0108123ec0b7.gif?imageMogr2/auto-orient/strip)
![](http://upload-images.jianshu.io/upload_images/3453618-e31c0108123ec0b7.gif?imageMogr2/auto-orient/strip) 

这里用多行1来实现部分图片在不可视区域,以上src的属性用占位图来替代,实际的图片地址绑定在data-src属性上。这样首屏的时候实际就加载了一张图片。

第一种(javascript)

(function(){

    var imgList,
        time = 250,
        delay,imgH,
        offset = 100;

   
     function _delay(obj){
         clearTimeout(delay);
         delay = setTimeout(function(){
            _imgload(obj);
         },time);
     }

     function _imgload(obj){
        imgH = obj[0].offsetHeight;
       // console.log(imgH);
        for(var i = 0,len = obj.length ; i < len ; i ++){
            if(obj[i].getAttribute('data-src')){
                 if(_isShow(obj[i])){
                   obj[i].src = obj[i].getAttribute('data-src');
                   obj[i].removeAttribute('data-src');
                }
            }  
        }
     }

     function _isShow(el){
        var coords = el.getBoundingClientRect();
         //console.log(coords);
         var left = coords.left ,
             top = coords.top,
             winH = document.documentElement.clientHeight || window.innerHeight;
        // return left >=0 && ( top >= 0 || top > - imgH ) && ( top <= winH + parseInt(offset) );   //只加载可视区域的图片            
            return left >=0 && top <= winH + parseInt(offset) //可视区域以上的图片也加载
     }
    
     function imgLoad(selector){

        var selector = selector || '.imgLazyLoad',
            node = document.querySelectorAll(selector),
            imgList = Array.apply(null,node);
        _delay(imgList);
        window.addEventListener('scroll',function(){
              _delay(imgList);
        },false);
     }
  
    imgLoad('.imgLazyLoad');
   

})();

第二种(jquery)

!(function($){
    /*
     options是个对象 非必填
     */
    $.fn.imgLazyLoad = function(options){
         var _windowH = $(window).height(),
             _delay, //函数节流
             _scrollTop = $(window).scrollTop();

         //默认参数
         var defaults = {
             time:500, //图片延迟加载的时间
             offset:250, //图片预加载的距离,
             className:"data-src"
         } ;
         var that = this;
         var options = $.extend({},defaults,options);
         

         function picLazyLoad(){
              clearTimeout(_delay);
              _delay = setTimeout(function(){
                  that.each(function(index,value){
                    //console.log($(value).offset().top);
                    if($(value).attr(options.className)){
                        _scrollTop = $(window).scrollTop();
                        if($(value).offset().top <= _windowH + _scrollTop + options.offset){
                            $(value).attr("src",$(value).attr(options.className));
                            $(value).removeAttr(options.className);
                        }
                    }
                    
                
                  });
              },options.time);

         } 

         $(window).on('scroll',function(){
                picLazyLoad();
         });
        picLazyLoad();
    };

})(jQuery);

使用方法:

(function(){
    
       $('.imgLazyLoad').imgLazyLoad({
        time:50, //间隔时间
        offset:100,//图片距离可视区域的偏移距离
        class:"data-src"
       });
})();

源码参考 https://github.com/chunxiao1991/imgLazyLoad

推荐阅读更多精彩内容