-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreload.js
108 lines (97 loc) · 3.68 KB
/
preload.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
;(function(name, definition) {
if (typeof define === 'function') {
define(definition)
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = definition()
} else {
this[name] = definition()
}
})('Preload', function() {
function Preload(picData, config) {
var picDataIsArray = Object.prototype.toString.call(picData) == '[object Array]'
if (!picDataIsArray || (picDataIsArray && picData.length == 0)) return
// 默认配置
var initConfig = {
handleFileLoad: function() {},
handleComplete: function() {},
handleError: function() {}
}
config = config || {}
this.config = this.extend(config, initConfig, false)
this.picData = picData
this.init()
}
Preload.prototype = {
// 初始化
init: function() {
var _this = this
var config = _this.config
var picData = _this.picData
// 所有图片数量
var total = picData.length
// 已经加载的图片数量
var loaded = 0
// 错误的图片数量
var errored = 0
function handle(obj, type) {
var para = {}
para.total = total
para.loaded = loaded
para.errored = errored
para.progress = (loaded + errored) / total
para.percent = parseInt(para.progress * 100) + "%"
if (type == "load" || type == "complete") {
if (config.handleFileLoad && typeof(config.handleFileLoad) == "function") {
config.handleFileLoad(obj, para)
}
} else if (type == "error" || type == "abort") {
if (config.handleError && typeof(config.handleError) == "function") {
config.handleError(obj, para)
}
}
if (para.progress == 1) {
if (config.handleComplete && typeof(config.handleComplete) == "function") {
config.handleComplete(obj, para)
}
}
obj = obj.onabort = obj.onload = obj.onerror = null
}
for (var i = 0; i < picData.length; i++) {
(function(m) {
var img = new Image()
img.src = picData[m]
if (img.complete) {
// console.log("有缓存")
loaded++
handle(img, "complete")
return
}
img.onload = function() {
loaded++
handle(img, "load")
}
img.onabort = function() {
errored++
handle(img, "abort")
}
img.onerror = function() {
errored++
handle(img, "error")
}
})(i)
}
},
// 对 json 对象进行更新扩展,会修改待更新扩展的对象,同时将其返回。
extend: function(destination, source, override, replacer) {
if (override === undefined) override = true
for (var property in source) {
if (override || !(property in destination)) {
if (replacer) replacer(property)
else destination[property] = source[property]
}
}
return destination
}
}
return Preload
})