//声明变量保存图片预加载的模块
var preloadImagesMoudle = (function () {
//声明一个空函数用于赋值给函数型变量
var emptyFn = function () {}
//声明数组变量保存图片预加载的两种方式
var preloadType = ['unorder', 'order'];
/*
* 定义一个名为PreloadImages的函数,作为图片预加载的模板类
* @param array 可选 imgs 预加载图片的连接
* @param function 可选 fn 图片加载完成后执行的自定义函数
* @param string 可选 type 图片预加载的类型
* @return void
* */
function PreloadImages (imgs, fn, type) {
try {
//检测参数,如果参数为空那么就给属性一个默认值
if (!imgs) {
this.imgs = [];
} else {
this.imgs = 'string'===typeof(imgs)? [imgs]: imgs;
}
if (!fn) {
this.fn = emptyFn;
} else {
this.fn = 'function'===typeof(fn)? fn:emptyFn;
}
if (!type) {
this.type = 'unorder';
} else {
if (preloadType.indexOf(type) > -1) {
this.type = type;
} else {
this.type = 'unorder';
}
}
} catch (err) {
console.error(err);
}
}
/*
* 定义一个名为unorder的函数,作为图片预加载的模板类的原型函数,用于无序加载图片
* @param void
* @return void
* */
PreloadImages.prototype.unorder = function (callback) {
var _imgs = this.imgs,
imgs_len = _imgs.length;
var imgObj = null;
for (var i = 0; i < imgs_len; i++) {
imgObj = new Image();
imgObj.onload = handleImageLoad;
imgObj.onerror = handleImageLoad;
imgObj.src = _imgs[i];
}
function handleImageLoad () {
callback();
}
}
/*
* 定义一个名为order的函数,作为图片预加载的模板类的原型函数,用于有序加载图片
* @param void
* @return void
* */
PreloadImages.prototype.order = function (callback) {
var _imgs = this.imgs,
imgs_len = _imgs.length;
var imgObj = null;
var count = 0;
(function preload () {
imgObj = new Image();
imgObj.onload = handleImageLoad;
imgObj.onerror = handleImageLoad;
function handleImageLoad () {
count = Math.min(imgs_len, ++count);
if (count < imgs_len) {
preload();
} else {
callback();
}
}
imgObj.src = _imgs[count];
imgObj = null;
})();
}
/*
* 定义一个名为init的函数,作为图片预加载的模板类的原型函数,用于启动原型对象的内部函数,完成图片加载
* @param void
* @return void
* */
PreloadImages.prototype.init = function () {
try {
//如果只想执行函数
if (0 === this.imgs.length && this.fn) {
this.fn();
return ;
}
if (0 === preloadType.indexOf(this.type)) {
this.unorder(this.fn);
} else if (1 === preloadType.indexOf(this.type)) {
this.order(this.fn);
} else {
this.unorder(this.fn);
}
} catch (err) {
console.log(err);
}
}
//作为模块的入口
return {
preloadImages : function (imgs, fn, type) {
var instance = new PreloadImages(imgs, fn, type);
instance.init();
}
}
})();
//使用范例
/*
var imgs = ['imgs/icon3.png', 'imgs/icon1.png', 'imgs/icon2.png', 'imgs/sword.png'];
var fn = function () {
console.log('图片加载完成');
}
preloadImagesMoudle.preloadImages(imgs, fn, 'order');
*/
js实现图片预加载模块化
最新推荐文章于 2024-07-07 18:28:23 发布