-
Notifications
You must be signed in to change notification settings - Fork 0
/
prior.js
102 lines (76 loc) · 2.2 KB
/
prior.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
(function() {
var Prior = Prior || {};
Prior.Loader = function(config) {
this.loadedImages = {};
this.loadedSounds = {};
this.successes = 0;
this.failures = 0;
this.imageQueue = config.images || [];
this.soundQueue = config.sounds || [];
this.doneCallback = config.whenDone || Function;
return this;
};
Prior.Loader.prototype = {
startDownload: function() {
if(this.imageQueue.length !== 0)
this.downloadImages();
if(this.soundQueue.length !== 0)
this.downloadAudio();
else
this.doneCallback();
return this;
},
downloadImages: function() {
var i;
for(i = 0; i < this.imageQueue.length; i+=1) {
var self = this,
path = this.imageQueue[i],
img = new Image();
img.addEventListener("load", function() {
console.log("Loaded Image: " + path);
self.successes += 1;
if(self.done()) self.doneCallback();
}, false);
img.addEventListener("error", function() {
console.log("Failed to load image: " + path);
self.failures += 1;
if(self.done()) self.doneCallback();
}, false);
img.src = path;
this.loadedImages[path] = img;
}
return this;
},
downloadAudio: function() {
var i;
for(i = 0; i < this.soundQueue.length; i+=1) {
var self = this,
path = this.soundQueue[i],
audio = new Audio();
audio.addEventListener("canplaythrough", function() {
console.log("Loaded Audio: " + path);
self.successes += 1;
if(self.done()) self.doneCallback();
}, false);
audio.addEventListener("error", function() {
console.log("Failed to load audio: " + path);
self.failures += 1;
if(self.done()) self.doneCallback();
}, false);
audio.src = path;
this.loadedSounds[path] = audio;
}
return this;
},
image: function(path) {
return (this.loadedImages[path] ? this.loadedImages[path] : null);
},
sound: function(path) {
return (this.loadedSounds[path] ? this.loadedSounds[path] : null);
},
done: function() {
return (this.successes + this.failures === this.imageQueue.length + this.soundQueue.length);
}
};
return (window.Prior = Prior);
})();