js元件之----圖片預載入
阿新 • • 發佈:2019-01-24
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);