图片预加载插件如何实现高效优化?

更新于
2026-09-30 21:23:33
2阅读来源:SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计206个文字,预计阅读时间需要1分钟。

图片预加载插件如何实现高效优化?

javascriptpreLoad.js(function($) { /* 构造方法 */ function preLoad(imgs, options) { this.imgs=(typeof imgs==='string') ? [imgs] : imgs; this.opts=$.extend({}, options); }})(jQuery);

preLoad.js

(function ($) { /*构造方法*/ function preLoad(imgs, options) { this.imgs = (typeof imgs === 'string') ? [imgs] : imgs; //$.extend 用一个或多个其他对象来扩展一个对象,返回被扩展的对象。 this.opts = $.extend({}, preLoad.DEFAULTS, options); this._unordered(); } preLoad.DEFAULTS = { each: null, // 每一张图片加载完毕后执行 all: null, // 所有图片加载完后执行 }; //原型链中添加方法 preLoad.prototype._unordered = function () { //无序加载 var imgs = this.imgs, opts = this.opts, count = 0, len = imgs.length; $.each(imgs, function (i, src) { if (typeof src !== 'string') { return; } var imgObj = new Image(); $(imgObj).on('load error', function () { opts.each && opts.each(count); if (count >= len - 1) { opts.all && opts.all(); } count++; }); imgObj.src = src; }); }; // $.extend() --> $.preLoad(); // $.fn.extend() --> $("#img").preLoad(); $.extend({ preload: function (imgs, opts) { new preLoad(imgs, opts); } }) })(jQuery); /* * 使用 * * $.preload(imgs,{ each:function (count) { //... }, all:function () { //... } }); * */

图片预加载插件如何实现高效优化?

本文共计206个文字,预计阅读时间需要1分钟。

图片预加载插件如何实现高效优化?

javascriptpreLoad.js(function($) { /* 构造方法 */ function preLoad(imgs, options) { this.imgs=(typeof imgs==='string') ? [imgs] : imgs; this.opts=$.extend({}, options); }})(jQuery);

preLoad.js

(function ($) { /*构造方法*/ function preLoad(imgs, options) { this.imgs = (typeof imgs === 'string') ? [imgs] : imgs; //$.extend 用一个或多个其他对象来扩展一个对象,返回被扩展的对象。 this.opts = $.extend({}, preLoad.DEFAULTS, options); this._unordered(); } preLoad.DEFAULTS = { each: null, // 每一张图片加载完毕后执行 all: null, // 所有图片加载完后执行 }; //原型链中添加方法 preLoad.prototype._unordered = function () { //无序加载 var imgs = this.imgs, opts = this.opts, count = 0, len = imgs.length; $.each(imgs, function (i, src) { if (typeof src !== 'string') { return; } var imgObj = new Image(); $(imgObj).on('load error', function () { opts.each && opts.each(count); if (count >= len - 1) { opts.all && opts.all(); } count++; }); imgObj.src = src; }); }; // $.extend() --> $.preLoad(); // $.fn.extend() --> $("#img").preLoad(); $.extend({ preload: function (imgs, opts) { new preLoad(imgs, opts); } }) })(jQuery); /* * 使用 * * $.preload(imgs,{ each:function (count) { //... }, all:function () { //... } }); * */

图片预加载插件如何实现高效优化?