jQuery插件图片懒加载lazyload

来自XXX的前言:

什么是ImageLazyLoad技术
在页面上图片比较多的时候,打开一张页面必然引起与服务器大数据量的 交互。尤其是对于高清晰的图片,占的几M的空间。ImageLazyLoad技术就是,当前可见界面的图片是加载进来的,而不可见页面(通过滚动条下拉可 见)中的图片是不加载的,这样势必会引起速度上质的提升。

实现原理:

当图片滚动到可视区时将图片加载进来。

图片不在可视区判断:

(一):图片距离页面顶端的高度 大于 窗口可视区的高度+window滚动条的scrollTop。

(二):图片距离页面顶端的高度+图片自身的高度 小于 window滚动条的scrollTop。

在lazyload中的实现(lazyload源码在后面):

var _this=$(this),  //this就是图片
    top=win.scrollTop(),  //win就是window
    imgTop=_this.offset().top,
    imgHeight=_this.outerHeight(true);
                    
if(top+win.height()>imgTop && imgTop+imgHeight>top){
    ...(图片在可视区了)
}

使用插件html准备(这是一个最简单的图片懒加载,或许这个已经达到正常需求):

html结构:

<div id="box">
     <img data-src="http://www.netbian.com/d/file/20150325/41ada82f8c880dc89bdb95e38e8777f4.jpg" src="loading.svg" />
        ......
    <img data-src="http://www.netbian.com/d/file/20140410/875d3e24e25a00761a71c4d46f130da0.jpg" src="loading.svg" />
</div>

解释:先用一张所有的图片(src)加载loading这个图片,然后给img加个data-src的属性,存储着图片本来的路径,然后就等js实现了。


js使用插件:

    <script>
        $('img').lazyload(/*{
            effect:'fadeIn',      //默认'fadeIn(淡入)',参数列表['none','fadeIn']
            fadeTime: 600,        //淡出时间,默认600ms,参数为number类型时间
            timeout: 260          //当用户看到图片时,是否立即加载图片,默认'(延迟)260ms',参数列表['none','time(number类型)']
        }*/)
  </script>

插件源码(兼容ie6):

;(function($){
    $.fn.extend({
        lazyload:function(Options){
            var _this=$(this),
                win=$(window),
                timer=null,
            
                settings=$.extend({
                    effect: 'fadeIn',
                    fadeTime: 600,
                    timeout: 260
                },Options);
            
            loading();    //开始执行已经到可视区的图片
            win.scroll(function(){
                settings.timeout=='none' ? loading() : ( clearTimeout(timer),timer=setTimeout(loading,settings.timeout) )    //是否延时加载
            });
            
            function loading(){
                _this.each(function(){
                    var _this=$(this),
                        top=win.scrollTop(),
                        imgTop=_this.offset().top,
                        imgHeight=_this.outerHeight(true);
                    
                    if(top+win.height()>imgTop && imgTop+imgHeight>top){
                        var dSrc=_this.attr('data-src');
                        if(dSrc==_this.attr('src')) return;    //图片已经显示,则返回
                        
                        $(new Image()).prop('src',dSrc).load(function(){    //替换图片URL
                            _this.attr('src',dSrc);
                            settings.effect=='fadeIn' && _this.css('opacity',0).animate({opacity:1},settings.fadeTime)
                        })
                    }
                })
            }
       return _this } }) })(jQuery);

--------- 平平的分割线 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

有了来自 @李明夕 的指导,然后就对lazyload进行了改造,添加了函数节流,其实之前的也用到了,只不过不知道专业名称-_-#,不过还是学到不少,函数节流文章链接:http://www.alloyteam.com/2012/11/javascript-throttle/

然后就是添加了事件移除功能,应该是有利于性能优化的。下面是改过后的代码:

;(function($){
    $.fn.extend({
        lazyload:function(Options){
            var gThis=$(this),
                win=$(window),
                
                throttle=function(fn,delay){    //函数节流,【执行函数,延迟时间】
                    var timer,
                        startTime=new Date();
                    
                    return function(){
                        clearTimeout(timer);
                        
                        if(!delay && new Date()-startTime>100){    //没有延迟,并判断延迟滚动时间的必须的时间
                            startTime=new Date();
                            fn()
                            
                        }else if(delay){
                            timer=setTimeout(function(){
                                startTime=new Date();
                                fn()
                            }, delay)
                        }
                    }
                },
            
                settings=$.extend({
                    effect: 'fadeIn',
                    fadeTime: 600,
                    delay: 400
                },Options);
            
            loading();    //开始便加载已经出现在可视区的图片
            win.on( 'scroll.lazyload', throttle(loading, settings.delay) );
            
            function loading(){
                if(!gThis.length) return win.off('scroll.lazyload');    //当所有的图片都加载完,移除窗口滚动事件
                
                gThis.each(function(){
                    var _this=$(this),
                        top=win.scrollTop(),
                        imgTop=_this.offset().top,
                        imgHeight=_this.outerHeight(true);
                    
                    if(top+win.height()>imgTop && imgTop+imgHeight>top){
                        gThis=gThis.not( _this );    //删除jQuery选择好的元素集合中已经被加载的图片元素
                        
                        var dSrc=_this.attr('data-src');
                        $(new Image()).prop('src',dSrc).load(function(){    //替换图片URL
                            _this.attr('src',dSrc);
                            settings.effect=='fadeIn' && _this.css('opacity',0).animate({opacity:1},settings.fadeTime)
                        })
                    }
                })
            }
            
            return $(this)
        }
    })
})(jQuery);

Demo地址:http://small.890m.com/lazyload/

原文地址:https://www.cnblogs.com/barrior/p/4470769.html