更多资源请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);