1. 程式人生 > >JS圖片預加載插件

JS圖片預加載插件

prev jpg ... def lib sogo itl reload btn

在開發H5項目中有時候會遇到要加載大量圖片的情況,利用預加載技術可以提高用戶瀏覽時的體驗。

1)概念:
懶加載也叫延遲加載:JS圖片延遲加載,延遲加載圖片或符合某些條件時才加載某些圖片。
預加載:提前加載圖片,當用戶需要查看時可直接從本地緩存中渲染。

2)區別:
兩種技術的本質:兩者的行為是相反的,一個是提前加載,一個是遲緩甚至不加載。懶加載對服務器前端有一定的緩解壓力作用,預加載則會增加服務器前端壓力。

服務器端區別:懶加載的主要目的是作為服務器前端的優化,減少請求數或延遲請求數。預加載可以說是犧牲服務器前端性能,換取更好的用戶體驗,這樣可以使用戶的操作得到最快的反映。

例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>preload</title>
    <style>
        * {
            margin: 0;
            pading: 0;
        }

        a {
            text-decoration: none;
        }

        .box 
{ text-align: center; } .btn { display: inline-block; height: 30px; line-height: 30px; border: 1px solid #ccc; background: #fff; padding: 0 10px; margin-right: 50px; color
: #333; } .btn:hover { background: #eee; } /*進度條樣式*/ .loading { position: fixed; top: 0; left: 0; bottom: 0; right: 0; //撐滿整個屏幕 background: #eee; text-align: center; font-size: 30px; font-weight: bold; } .progress { margin-top: 300px; } </style> </head> <body> <!--無序預加載需要寫進度條,當加載完畢後才能操作; 有序預加載可以不寫進度條,加載完第一張後立即加載第二張、第三張、第四張... --> <div class="box"> <img src="http://image.hnol.net/c/2010-11/14/21/201011142147143181-239867.jpg" id="img" alt="pic" width="1000"> <p> <a href="javascript:;" class="btn" data-control="prev">上一張</a> <a href="javascript:;" class="btn" data-control="next">下一張</a> </p> </div> <!--進度條--> <div class="loading"> <p class="progress">0%</p> </div> <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> <script src="~/Scripts/preload.js"></script> <script> var imgs = [http://image.hnol.net/c/2010-11/14/21/201011142147143181-239867.jpg, http://www.picperweek.com/resource/image/dbc3c16b-5fc6-48e5-aa48-c64739739da2.png, http://imgstore.cdn.sogou.com/app/a/100540002/406526.jpg], index = 0, len = imgs.length; $progress = $(.progress); //有序預加載,可以不用寫進度條部分,如果有寫,需要手動配置each()、all()方法 // $.preload(imgs,{ // order:‘ordered‘ // }); //調用無序預加載 --imgs 數組存放預加載的圖片 $.preload(imgs, { //每張圖片加載(load事件)一次觸發一次each() each: function (count) { //進度條顯示百分比進度 $progress.html(Math.round((count + 1) / len * 100) + %); }, //加載完畢 all: function () { $(.loading).hide(); document.title = 1/ + len;//初始化第一張 } }); //未封裝成插件的無序預加載 // $.each(imgs,function(i,src){ // var imgObj = new Image(); //Image()實例用於緩存圖片 // // $(imgObj).on(‘load error‘,function(){ // $progress.html(Math.round((count + 1) / len * 100) + ‘%‘); // // if(count >= len - 1){ // $(‘.loading‘).hide(); // document.title = ‘1/‘ + len; // } // count++;//每加載完一張圖片count加1 // }); // // imgObj.src = src;//緩存圖片 // }); //上一頁,下一頁按鈕 $(.btn).on(click, function () { if (prev === $(this).data(control)) { index = Math.max(0, --index); } else { index = Math.min(len - 1, ++index); } document.title = (index + 1) + / + len; $(img).attr(src, imgs[index]); }); </script> </body> </html>

插件:

; (function ($) {

    function PreLoad(imgs, options) {
        //保存圖片到數組
        this.imgs = (typeof imgs === ‘string‘) ? [imgs] : imgs;
        this.opts = $.extend(PreLoad.defaults, options);

        // this._unordered();//如果只有無序預加載
        if (this.opts.order === ‘ordered‘) {
            this._ordered();
        } else {
            this._unordered();//默認是無序預加載
        }
    };
    PreLoad.defaults = {
        order: ‘unordered‘, //指定默認加載方式為無序
        each: null, //每一張圖片加載完畢後執行
        all: null //所有圖片加載完畢後執行
    };
    //有序預加載
    PreLoad.prototype._ordered = function () {
        var opts = this.opts,
            imgs = this.imgs,
            len = imgs.length,
            count = 0;

        load();
        function load() {
            var imgObj = new Image();

            $(imgObj).on(‘load error‘, function () {
                //相當於if(opts.each){ opts.each(); } ,如果有配置each()方法則調用,後面的all()同理
                opts.each && opts.each(count);

                if (count >= len) {
                    //所有圖片加載完畢
                    opts.all && opts.all();
                } else {
                    //如果沒加載完,繼續調用自身加載下一張
                    load();
                }
                count++;
            });

            imgObj.src = imgs[count];//緩存圖片
        };
    };

    //無序加載
    PreLoad.prototype._unordered = function () {
        var imgs = this.imgs,
            opts = this.opts,
            count = 0,
            len = imgs.length;

        $.each(imgs, function (i, src) {
            //判斷圖片數組中的每一項是否為字符串,不是字符串會導致出錯,因此返回
            if (typeof src != ‘string‘) return;

            var imgObj = new Image();

            $(imgObj).on(‘load error‘, function () {
                //判斷opts.each是否存在,不存在則不執行
                opts.each && opts.each(count);

                if (count >= len - 1) {
                    //判斷opts.all是否存在,存在則執行
                    opts.all && opts.all();
                }
                count++;
            });

            imgObj.src = src;//緩存圖片
        });
    };

    //由於不用具體的對象去調用,因此用$.extend(object)掛載插件.
    $.extend({
        //preload為插件名
        preload: function (imgs, opts) {
            new PreLoad(imgs, opts);
        }
    });

})(jQuery);

JS圖片預加載插件