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

圖片預加載

內容 變量 html src 生成 return each err default

//圖片預加載
(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);

圖片預加載