图片预加载

//图片预加载
(function ($) {
    //imgs图片数组,参数
    function PreLoad(imgs,options){
        //传进来的如果是字符串,转成数组
        this.imgs = (typeof imgs === 'string') ? [imgs] :imgs;
        //将options和default融合生成一个对象,将option覆盖default的内容声称对象。
        this.opts = $.extend({},PreLoad.DEFAULTS,options);

        this._unoredered();
    }
    
    //默认变量
    PreLoad.DEFAULTS = {
        each:null,//每一张图片加载完毕之后执行
        all:null//所有图片加载完毕之后执行
    }
    //无序加载
    PreLoad.prototype._unoredered = function(){
        var imgs = this.imgs,
            opts = this.opts,
            count = 0,
            len = imgs.length;

        $.each(imgs, function (i,src){
            //如果不是src就return
            if (typeof src!='string') return;
            
            var imgObj = new Image();

            $(imgObj).on('load error', function () {
                //$progress.html(Math.round((count+1)/len * 100) + '%');
                opts.each && opts.each(count);

                if(count >= len-1){
                    opts.all && opts.all();
                    //$('.loading').hide();
                }
                count++;
            });

            imgObj.src = src;
        });
    }

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

 

posted @ 2018-01-22 13:08  亦心晗  阅读(144)  评论(0编辑  收藏  举报