封装了个图片预加载 · KYLE'S BLOG

最近一个项目,首页图片太多,便在网上找资料搜寻解决方法,搜集了一些方法,并进行了封装。

最简单的方法是把图片的src值放在一个数组中,用for循环对数组进行遍历,创建图片对象并将遍历的src值加到图片对象的src属性上,之后在写一个onload的回调函数就可以使用图片对象了。demo代码如下:

      
      
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', //無序預加載
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


猜你喜欢

转载自www.cnblogs.com/wangziqiang123/p/11618465.html
今日推荐