lazyload懶加載的使用

懶加載的意義(為什么要使用懶加載)

對頁面加載速度影響最大的就是圖片,一張普通的圖片可以達到幾M的大小,而代碼也許就只有幾十KB。當頁面圖片很多時,頁面的加載速度緩慢,幾S鐘內頁面沒有加載完成,也許會失去很多的用戶。

所以,對于圖片過多的頁面,為了加速頁面加載速度,所以很多時候我們需要將頁面內未出現在可視區域內的圖片先不做加載, 等到滾動到可視區域后再去加載。這樣子對于頁面加載性能上會有很大的提升,也提高了用戶體驗。

原理

將頁面中的img標簽src指向一張小圖片或者src為空,然后定義data-src(這個屬性可以自定義命名,我才用data-src)屬性指向真實的圖片。src指向一張默認的圖片,否則當src為空時也會向服務器發送一次請求。可以指向loading的地址。
當載入頁面時,先把可視區域內的img標簽的data-src屬性值負給src,然后監聽滾動事件,把用戶即將看到的圖片加載。這樣便實現了懶加載。

懶加載的使用

1.引用< script src="http://a.tbcdn.cn/apps/baron/js/??lib/tmm/tmm.js,lib/lazyload/lazyload.js?20121015"></script>

2.對于要懶加載的圖片進行如下屬性設置。< img src="http://a.tbcdn.cn/mw/webapp/fav/img/grey.gif" dataimg="http://img03.taobaocdn.com/tps/i3/T1xl4_FlFaXXcLmU_5-305-317.png" />
其中src為未加載時的圖片,dataimg為實際要加載的圖片。

3.執行lazyload.init();

4.分tab的懶加載。判斷tab把下面的圖片有沒加載過。根據loaded屬性判斷,還要對非當前tab所屬的圖片進行class lazy去掉。對已加載的loaded為true的圖片,不加lazy屬性

5.注意lazyload.init()的執行時機,如果在dom ready階段執行,會下載所有圖片,不能實現懶加載。要在winow.onload完成這個階段去執行。

代碼實例

<!doctype html>
<html lang="en">

    <head>
        <meta charset="UTF-8" />
        <title>懶加載實例</title>
        <style type="text/css">
        /*一定要有預先高度*/
            img{
                width: 600px;
                height: 260px;
            }
        </style>
    </head>

    <body>
        <div>
            ![](http://upload-images.jianshu.io/upload_images/6857128-38e3ae1aa6324e92.gif?imageMogr2/auto-orient/strip)
        </div>
        <div>
            ![](http://upload-images.jianshu.io/upload_images/6857128-38e3ae1aa6324e92.gif?imageMogr2/auto-orient/strip)
        </div>
        <div>
            ![](http://upload-images.jianshu.io/upload_images/6857128-38e3ae1aa6324e92.gif?imageMogr2/auto-orient/strip)
        </div>
        <div>
            ![](http://upload-images.jianshu.io/upload_images/6857128-38e3ae1aa6324e92.gif?imageMogr2/auto-orient/strip)
        </div>
        <div>
            ![](http://upload-images.jianshu.io/upload_images/6857128-38e3ae1aa6324e92.gif?imageMogr2/auto-orient/strip)
        </div>
        <div>
            ![](http://upload-images.jianshu.io/upload_images/6857128-38e3ae1aa6324e92.gif?imageMogr2/auto-orient/strip)
        </div>
        <div>
            ![](http://upload-images.jianshu.io/upload_images/6857128-38e3ae1aa6324e92.gif?imageMogr2/auto-orient/strip)
        </div>
        <div>
            ![](http://upload-images.jianshu.io/upload_images/6857128-38e3ae1aa6324e92.gif?imageMogr2/auto-orient/strip)
        </div>
    </body>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
        var lazyload = {
          init : function(opt){
            var that = this,
            op = {
                anim: true,
                extend_height:0,
                selectorName:"img",
                realSrcAtr:"dataimg"
            };
            // 合并對象,已有的{anim:true}+用戶自定義對象。也就是op = op + opt
            $.extend(op,opt);
            // 調用lazyload.img.init(op)函數
            that.img.init(op);
        
          },
        
          img : {
            init : function(n){
        
              var that = this,
              selectorName = n.selectorName,
              realSrcAtr = n.realSrcAtr,
              anim = n.anim;
//              console.log(n);
        
              // 要加載的圖片是不是在指定窗口內
              function inViewport( el ) {
                  // 當前窗口的頂部
                var top = window.pageYOffset,
                // 當前窗口的底部
               btm = window.pageYOffset + window.innerHeight,
                // 元素所在整體頁面內的y軸位置
               elTop = $(el).offset().top;
                // 判斷元素,是否在當前窗口,或者當前窗口延伸400像素內
                return elTop >= top && elTop - n.extend_height <= btm;
              }
        
              // 滾動事件里判斷,加載圖片
               $(window).on('scroll', function() {
                  $(selectorName).each(function(index,node) {
                    var $this = $(this);
                    
                    if(!$this.attr(realSrcAtr) || !inViewport(this)){
                      return;
                    }
                   
                    act($this);
        
                  })
                }).trigger('scroll');
        
               // 展示圖片
               function act(_self){
                      // 已經加載過了,則中斷后續代碼
                   if (_self.attr('lazyImgLoaded')) return;
                    var img = new Image(), 
                    original = _self.attr('dataimg');
                    // 圖片請求完成后的事件,把dataimg指定的圖片,放到src里面,瀏覽器顯示
                    img.onload = function() {
                        _self.attr('src', original);
                        anim && _self.css({ opacity: .2 }).animate({ opacity: 1 }, 280);
                    };
                    // 當你設置img.src的時候,瀏覽器就在發送圖片請求了
                    original && (img.src = original);
                     _self.attr('lazyImgLoaded', true);
               }
            }
          }
        };
        
        /*
         * selectorName,要懶加載的選擇器名稱
         * extend_height  擴展高度
         * anim  是否開啟動畫
         * realSrcAtr  圖片真正地址*/
        lazyload.init({
            anim:false,
            selectorName:".samLazyImg"
        });
    </script>

</html>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,841評論 25 708
  • 原文轉自: https://troyyang.com/2017/08/06/hexo-lazyload-image...
    troyyang閱讀 4,259評論 0 3
  • tips:接下去會在github寫博客,簡書不再更新和修改文章,歡迎大家逛逛我的新博客點擊查看 ,我會盡量用更容易...
    aermin閱讀 2,140評論 0 34
  • OC中的位運算和C/C++語言的位運算是一樣的。一般有 &(按位與),| (按位或),~ (按位取反),<<(左移...
    結局怎么寫閱讀 5,497評論 1 10
  • 沉悶的午后突然間變得躁動起來,風扯開了雨季的帷幕,傾刻間天與地變得模糊。端坐在寢室里的我看到外邊這般不安靜的景象心...
    謀也閱讀 146評論 0 1