jquery图片预加载插件

发布时间:2019-05-23 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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);

脚本宝典总结

以上是脚本宝典为你收集整理的jquery图片预加载插件全部内容,希望文章能够帮你解决jquery图片预加载插件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。