首页 小组 问答 话题 好文 素材 用户 唠叨 我的社区

[分享]jquery图片预加载插件

风轻yLv.1种子选手
2024-09-12 15:20:21
0
39

更多资源请Star:https://github.com/maidishike...

图片预加载插件

网站开发时经常需要在某个页面需要实现对大量图片的浏览,就会出现网页假死的现象,所以为了让图片在转换的时候不出现等待,我们最好是先让图片预先加载到本地,让用户无需等待过长的时间就能看到其他图片,优化用户体验

调用方式

请预先引入jquery

$.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);
风轻y
风轻y

40 天前

签名 :   39       0
评论
站长交流