jquery圖片預加載插件

更多資源請Star:https://github.com/maidishike...javascript

圖片預加載插件

網站開發時常常須要在某個頁面須要實現對大量圖片的瀏覽,就會出現網頁假死的現象,因此爲了讓圖片在轉換的時候不出現等待,咱們最好是先讓圖片預先加載到本地,讓用戶無需等待過長的時間就能看到其餘圖片,優化用戶體驗java

調用方式

請預先引入jqueryjquery

$.preload(imgs, { // imgs: 圖片數組或字符串 ['1.jgp', '2.jpg'] 或者 '1.jpg'
  order: 'ordered', // 默認無序加載
  each: function(count) {
    // 單個圖片加載完成
  },
  all: function() {
    // 全部圖片加載完成
  }
});

插件代碼

(function($) {
  function PreLoad (imgs, opts) {
    this.imgs = (typeof imgs === 'string') ? [imgs] : imgs;
    this.opts = $.extend({}, PreLoad.DEFAULTS, opts);
    if (this.opts.order === 'ordered') {
      this._ordered(); // 有序加載
    } else {
      this._unordered(); // 無序加載
    }
  }
  PreLoad.DEFAULTS = {
    order: 'unordered', //默認進行無序預加載
    each: null, // 單個圖片加載完成後執行的方法
    all: null // 全部圖片加載完成後執行的方法
  };

  PreLoad.prototype._ordered = function () { // 有序加載
    var imgs = this.imgs, len = imgs.length, count = 0, opts = this.opts;
    load();
    function load () {
      var img = new Image();
      $(img).on('load error', function() {
        opts.each && opts.each(count);
        if (count >= len) {
          // 全部圖片加載完畢
          opts.all && opts.all();
        } else {
          load();
        }
        count++;
      });
      img.src = imgs[count];
    }
  };
  PreLoad.prototype._unordered = function() { // 無序加載
    var imgs = this.imgs, len = imgs.length, count = 0, opts = this.opts;
    imgs.forEach(function(elem) {
      var img = new Image();
      $(img).on('load error', function(){
         opts.each && opts.each(count);
        if (count >= len -1) {
          opts.all && opts.all();
        }
        count++;
      });
      img.src = elem;
    });
  };
  $.extend({
    preload: function(imgs, opts) {
      new PreLoad(imgs, opts);
    }
  });
})(jQuery);
相關文章
相關標籤/搜索