您的位置:首页 > Web前端 > JavaScript

js组件之----图片预加载

2018-01-22 21:23 134 查看
jquery实现的图片预加载原理, 没有丰富的功能,但是基本功能可以实现.

如有雷同,纯属看了同一门课程…

/**
* 图片预加载
* dependencies: jQuery
* recommend: <script src='https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js'></script>
*/

(function(doc, win, $) {
function Preload(imgs, opts) {
this.imgs = (typeof imgs === 'string') ? [imgs] : imgs;//若传入的不是数组,就转化为数组
this.opts = $.extend({}, Preload.DEFAULTS, opts);//浅拷贝

if (this.opts.order === 'unorder') {
this._unordered();//无须加载
} else {
this._ordered();//有序加载
}
}
Preload.DEFAULTS = {
order: 'unorder',//默认使用无须加载
each: null, //每张图片加载完成后执行
all: null //所有图片加载完成后执行
};
Preload.prototype._ordered = function() {//将方法添加进对象的原型中
var imgs = this.imgs,
opts = this.opts,
len = this.imgs.length,
count = 0;

function orload() {
var oImg = new Image();
$(oImg).on('load error', function() { //绑定事件
if (count >= len) {
return; //所有图片加载完毕
} else {
orload();
}
});
oImg.src = imgs[count++];
}
}

Preload.prototype._unordered = function() {
var imgs = this.imgs,
opts = this.opts,
len = this.imgs.length,
count = 0;

$.each(imgs, function(i, src) {
if (typeof src != 'string') return;
var oImg = new Image();

$(oImg).on('load error', function() {
opts.each && opts.each(count);
if (count >= len - 1) {
opts.all && opts.all();
}
count++;
});

oImg.src = src;//上面new的图片对象在添加src值之后才开始加载
});
};

$.extend({ //将Predload对象添加进jquery的原型中
preload: function(imgs, opts) {
new Preload(imgs, opts);
}
});
})(document, window, jQuery);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript jquery