基本信息
源码名称:图片预加载(loading.js)
源码大小:2.40KB
文件格式:.js
开发语言:js
更新时间:2019-03-29
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 1 元 
   源码介绍

封装图片预加载功能,便于直接调用

【使用方法】

//使用方式:
//   var imgs = [];     //存放图片地址的数组
//  $.Load(imgs ,{
//      order : 'unordered',         //是否有序预加载,默认无序unordered,有序为ordered
//      each : function(count){
//          每张图片加载完成的操作
//      },
//      all : function(){
//          所有图片加载完成之后的操作
//      }
// })

(function ($) {
    function UnorderedLoad(imgs , options){
        this.imgs = (typeof imgs === 'string') ? [imgs] : imgs;
        this.opts = $.extend({}, UnorderedLoad.defaults, options);   //后两个对象融合生成新的{}对象(即第三个覆盖第二个,生成第一个对象),返回给this.opts保存

        if(this.opts.order === 'ordered'){
            this.ordered();
        }else{
            this.unordered();
        }
    };
    UnorderedLoad.defaults = {
        order : 'unordered',  //是否有序预加载,默认无序
        each : null,    //每张图片加载完成之后执行
        all : null      //所有的图片加载完成之后执行
    };
    UnorderedLoad.prototype.ordered = function(){   //有序加载
        var imgs = this.imgs,
            opts = this.opts,
            count = 0,
            len = imgs.length;

        function load(){
            var imgObj = new Image();
            $(imgObj).on('load error',function(){
                opts.each && opts.each(count);        //判断方法是否存在,若存在,则执行
                if(count >= len){
                    //所有图片加载完成
                    opts.all && opts.all();
                }else{
                    load();
                }
                count ;
            });
            imgObj.src = imgs[count];
        };

        load();
    },
    UnorderedLoad.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(count);

                if(count >= len - 1){
                    opts.all && opts.all();
                }

                count ;
            });
            imgObj.src = src;
        });
    };

    $.extend({
        Load : function(imgs,opts){
            new UnorderedLoad(imgs,opts);
        }
    });
})(jQuery);



//使用方式:
//   var imgs = [];     //存放图片地址的数组
//  $.Load(imgs ,{
//      order : 'unordered',         //是否有序预加载,默认无序unordered,有序为ordered
//      each : function(count){
//          每张图片加载完成的操作
//      },
//      all : function(){
//          所有图片加载完成之后的操作
//      }
// })