Created
November 11, 2016 20:39
-
-
Save rvighne/16fb86ab94cf67f4a36cacbd625e3ff1 to your computer and use it in GitHub Desktop.
Very simple interface for loading resources (esp. images, audio for e.g. game sprites) asynchronously, attaching callbacks to individual resources, and waiting for all queued resources to be loaded.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
/* Simple async resource loader */ | |
class Loader { | |
constructor() { | |
this.promises = []; | |
} | |
get(src, type = Image) { | |
let promise = new Promise(function (fulfill, reject) { | |
let res = new type; | |
res.onload = function () { | |
fulfill(res); | |
}; | |
res.onerror = function () { | |
reject(); | |
}; | |
res.src = src; | |
}); | |
this.promises.push(promise); | |
return promise; | |
} | |
// Resolves when all queued resources have finished loading | |
// IMPORTANT: To release memory and to clear promises for failed downloads, | |
// wait() immediately clears the queue as a side-effect | |
wait() { | |
let promise = Promise.all(this.promises); | |
this.promises = []; | |
return promise; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment