Encapsulates pictures preloaded · KYLE'S BLOG

Recently a project Home picture too much, they search the Internet to find information on the solution, we collected some methods, and encapsulation.

The easiest way is to picture the src value in an array, the array is traversed by a for loop, create images and objects added to the picture src attribute of an object traversing the src value, after writing a callback function in onload you can use a picture of the object. demo code is as follows:

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
      
      
( function () {
function (imgs, options) {
this.imgs = ( typeof imgs === 'string') ? [imgs] : imgs;
this.opts = $.extend({}, ProLoad.DEDAULTS, options);
if ( this.opts.order === 'ordered') {
this._ordered();
} else{
this._unordered();
}
}
ProLoad.DEDAULTS = {
Order: 'unordered The' , // disorder preloaded
each: null, //每一张图片加载完毕后执行
all: null //所有图片加载完毕后执行
};
ProLoad.prototype._ordered = function () {
var opts = this.opts,
imgs = this.imgs,
len = imgs.length,
count = 0;
load();
function load() {
var imgObj = new Image();
$(imgObj).on( 'load error', function () {
if (count >= len) {
//所有图片加载完毕
} else{
load()
}
count++;
});
imgObj.src = imgs[count];
}
};
ProLoad.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: function (imgs, opts) {
new ProLoad(imgs,opts);
}
})
})(jQuery);

用法:

  1. 引入jquery库和以上代码
  2. $.progress(imgs, opts)
  3. 具体看实例github

鸣谢

Alex Wang老师的教程

原文:大专栏  封装了个图片预加载 · KYLE'S BLOG


Guess you like

Origin www.cnblogs.com/wangziqiang123/p/11618465.html