blob: ad42b17b0bdfb240be22a6a24670ec797c62ca4a (
plain)
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
|
module.exports = (function(){
function Loader (readyCallback, view){
this.assets = {};
this.images = [];
this.readyCallback = readyCallback || function(){};
this.count = 0
this.view = view
this.loaded = false
}
// Set the callback when the loader is ready
Loader.prototype.onReady = function(readyCallback){
this.readyCallback = readyCallback || function(){};
}
// Register an asset as loading
Loader.prototype.register = function(s){
this.assets[s] = false;
this.count += 1
}
// Signal that an asset has loaded
Loader.prototype.ready = function(s){
// window.debug && console.log("ready >> " + s);
this.assets[s] = true;
if (this.loaded) return;
this.view && this.view.update( this.percentRemaining() )
if (! this.isReady()) return;
this.loaded = true;
if (this.view) {
this.view && this.view.finish(this.readyCallback)
}
else {
this.readyCallback && this.readyCallback();
}
}
// (boolean) Is the loader ready?
Loader.prototype.isReady = function(){
return ! Object.keys(this.assets).some( (key) => {
return ! this.assets[key]
})
}
// (float) Percentage of assets remaining
Loader.prototype.percentRemaining = function(){
return this.remainingAssets() / this.count
}
// (int) Number of assets remaining
Loader.prototype.remainingAssets = function(){
var n = 0;
for (var s in this.assets) {
if (this.assets.hasOwnProperty(s) && this.assets[s] != true) {
n++;
// console.log('remaining: ' + s);
}
}
return n;
}
// Preload the images in config.images
Loader.prototype.preloadImages = function(images){
this.register("preload");
for (var i = 0; i < images.length; i++) {
this.preloadImage(images[i]);
}
this.ready("preload");
}
Loader.prototype.preloadImage = function(src, register, cb){
if (! src || src == "none") return;
var _this = this;
if (! cb && typeof register === "function") {
cb = register
register = null
}
if (register) {
this.register(src);
}
var img = new Image(), loaded = false;
img.onload = function(){
if (loaded) return
loaded = true
if (cb) {
cb(img);
}
if (register) {
_this.ready(src);
}
}
img.src = src;
if (img.complete) img.onload();
_this.images.push(img);
}
return Loader;
})();
|