forked from jwagner/Neonflames
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.js
87 lines (84 loc) · 2.74 KB
/
loader.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
(function(){
window.loader = {};
loader.Loader = function Loader(root){
this.root = root || '';
this.pending = 0;
this.total = 0;
this.failed = 0;
this.resources = {};
}
loader.Loader.prototype = {
load: function(resources) {
for(var i = 0; i < resources.length; i++) {
var resource = resources[i];
// allows loading in multiple stages
if(resource in this.resources){
continue;
}
this.pending ++;
this.total ++;
if(/\.(jpe?g|gif|png)$/.test(resource)){
this._loadImage(resource);
}
else if(/\.(og(g|a)|mp3)$/.test(resource)){
this._loadAudio(resource);
}
else if(/\.json$/.test(resource)){
this._loadJSON(resource);
}
else {
this._loadData(resource);
}
}
if(this.pending === 0 && this.onready){
var self = this;
// always call AFTER the mainloop
// multiple load calls can result in
// multiple onready() calls!
window.setTimeout(function () {
if(self.onready){
self.onready();
}
}, 1);
}
},
onready: null,
_loadImage: function(src) {
var self = this;
var img = document.createElement('img');
img.onload = function() {
self._success(src, img);
}
img.onerror = function (e) {
self._error(src, e);
}
img.src = this.root + src;
},
_loadJSON: function(src){
var self = this;
$.getJSON(this.root + src)
.success(function(data) { self._success(src, data); })
.error(function(error) { self._error(src, error); });
},
_loadData: function(src){
var self = this;
$.get(this.root + src)
.success(function(data) { self._success(src, data); })
.error(function(error) { self._error(src, error); });
},
_success: function(src, data) {
this.resources[src] = data;
this.pending --;
if(this.pending === 0 && this.onready){
this.onready();
}
},
_error: function(src, error) {
this.pending --;
this.failed ++;
this.resources[src] = null;
error.src = src;
throw error;
}
};
})();