1. 程式人生 > >滾屏到相應位置才載入圖片-優化頁面訪問速度

滾屏到相應位置才載入圖片-優化頁面訪問速度

一個頁面圖片太多了就有壓力。但如果總是分頁,每頁雞碎那麼多,使用者又會很煩。

可以滾屏到相應位置才載入圖片,這樣就皆大歡喜了。

原理如下:

1、使用jquery

2、需要動態載入的<img>增加一個屬性(自己建立的)data-url=真正圖片路徑,而將src=一個只有1畫素的透明GIF,style設定一個不停地轉圈的等待圖片作為背景,class="scl"

3、相應的jquery對凡是class="scl"的,當螢幕可見時,就將data-url來替換src,這樣就可以實現動態載入。在使用者這邊看來,拉動螢幕到這些圖片,會看見它們由一個不停地轉動的圖片變為真正想看的圖片。

程式碼如下:

jquery.scrollLoading.js

[javascript] view plaincopyprint?
  1. /*!
  2. * jquery.scrollLoading.js
  3. * by zhangxinxu  http://www.zhangxinxu.com
  4. * 2010-11-19 v1.0
  5. * 2012-01-13 v1.1 偏移值計算修改 position → offset
  6. */
  7. (function($) { 
  8.     $.fn.scrollLoading = function(options) { 
  9.         var defaults = { 
  10.             attr: "data-url"
  11.         }; 
  12.         var params = $.extend({}, defaults, options || {}); 
  13.         params.cache = []; 
  14.         $(this).each(function() { 
  15.             var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]); 
  16.             if (!url) { return; } 
  17.             //重組
  18.             var data = { 
  19.                 obj: $(this), 
  20.                 tag: node, 
  21.                 url: url 
  22.             }; 
  23.             params.cache.push(data); 
  24.         }); 
  25.         //動態顯示資料
  26.         var loading = function() { 
  27.             var st = $(window).scrollTop(), sth = st + $(window).height(); 
  28.             $.each(params.cache, function(i, data) { 
  29.                 var o = data.obj, tag = data.tag, url = data.url; 
  30.                 if (o) { 
  31.                     post = o.offset().top; posb = post + o.height(); 
  32.                     if ((post > st && post < sth) || (posb > st && posb < sth)) { 
  33.                         //在瀏覽器視窗內
  34.                         if (tag === "img") { 
  35.                             //圖片,改變src
  36.                             o.load(function() { 
  37.                                 o.removeClass("wimg"); 
  38.                             }); 
  39.                             o.attr("src", url); 
  40.                         } else
  41.                             o.load(url); 
  42.                         } 
  43.                         data.obj = null
  44.                     } 
  45.                 } 
  46.             }); 
  47.             returnfalse
  48.         }; 
  49.         //事件觸發
  50.         //載入完畢即執行
  51.         loading(); 
  52.         //滾動執行
  53.         $(window).bind("scroll", loading); 
  54.     }; 
  55. })(jQuery); 
/*!
 * jquery.scrollLoading.js
 * by zhangxinxu  http://www.zhangxinxu.com
 * 2010-11-19 v1.0
 * 2012-01-13 v1.1 偏移值計算修改 position → offset
*/
(function($) {
    $.fn.scrollLoading = function(options) {
        var defaults = {
            attr: "data-url"
        };
        var params = $.extend({}, defaults, options || {});
        params.cache = [];
        $(this).each(function() {
            var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]);
            if (!url) { return; }
            //重組
            var data = {
                obj: $(this),
                tag: node,
                url: url
            };
            params.cache.push(data);
        });

        //動態顯示資料
        var loading = function() {
            var st = $(window).scrollTop(), sth = st + $(window).height();
            $.each(params.cache, function(i, data) {
                var o = data.obj, tag = data.tag, url = data.url;
                if (o) {
                    post = o.offset().top; posb = post + o.height();
                    if ((post > st && post < sth) || (posb > st && posb < sth)) {
                        //在瀏覽器視窗內
                        if (tag === "img") {
                            //圖片,改變src
                            o.load(function() {
                                o.removeClass("wimg");
                            });
                            o.attr("src", url);
                        } else {
                            o.load(url);
                        }
                        data.obj = null;
                    }
                }
            });
            return false;
        };

        //事件觸發
        //載入完畢即執行
        loading();
        //滾動執行
        $(window).bind("scroll", loading);
    };
})(jQuery);

頁面 [html] view plaincopyprint?
  1. <styletype="text/css">
  2.     .scl{background:url(/img/loading.gif) no-repeat center;} 
  3.     .wimg{width:300px;height:200px;} 
  4. </style>
    <style type="text/css">
        .scl{background:url(/img/loading.gif) no-repeat center;}
        .wimg{width:300px;height:200px;}
    </style>
[html] view plaincopyprint?
  1. <scripttype="text/javascript"src="/js/jquery.scrollLoading.js?ver=120308_3"></script>
  2. <scripttype='text/javascript'src='http://cbjs.baidu.com/js/m.js'></script>
    <script type="text/javascript" src="/js/jquery.scrollLoading.js?ver=120308_3"></script>

    <script type='text/javascript' src='http://cbjs.baidu.com/js/m.js'></script>

[html] view plaincopyprint?
  1. <ahref='/show.aspx?id=33210947&i=1'target='_blank'><imgclass="scl"src='/img/pixel.gif'data-url="Upload/2/PicMiniSize/2012-3-9/201203090246063866.jpg"/></a><br/><ahref='/show.aspx?id=33210947&i=1'target='_blank'>成熟女人豔如桃……(第一百零五輯)</a>
                <a href='/show.aspx?id=33210947&i=1' target='_blank'><img class="scl" src='/img/pixel.gif' data-url="Upload/2/PicMiniSize/2012-3-9/201203090246063866.jpg"/></a><br/><a href='/show.aspx?id=33210947&i=1' target='_blank'>成熟女人豔如桃……(第一百零五輯)</a>

[html] view plaincopyprint?
  1. <scripttype="text/javascript">
  2.     $(function() { 
  3.         $(".scl").scrollLoading(); 
  4.     }); 
  5. </script>
<script type="text/javascript">
    $(function() {
        $(".scl").scrollLoading();
    });
</script>

這裡有一個問題,就是有時真正圖片的尺寸不一定能事先知道,所以一般不指定 width 和 height。但這裡暫代圖片只有1畫素,不指定足夠大的尺寸,根本看不到不停地轉圈等待那個效果;但如果指定了,比如width=300px,height=200px,那真正圖片出來後,也只有這麼大,並且看起來變形。解決辦法是,載入前指定width=300px,height=200px,載入完成後,再將這個指定去掉。

所以我們定義了一個CSS class :.wimg{width:300px;height:200px;},載入完成後去掉這個wimg。jquery.scrollLoading.js中有這麼一句:

[javascript] view plaincopyprint?
  1. //圖片,改變src
  2.                             o.load(function() { 
  3.                                 o.removeClass("wimg"); 
  4.                             }); 
//圖片,改變src
                            o.load(function() {
                                o.removeClass("wimg");
                            });

參照文章