jquery图片预加载插件

更多资源请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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值