Skip to content

Instantly share code, notes, and snippets.

@rvighne
Created November 11, 2016 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rvighne/16fb86ab94cf67f4a36cacbd625e3ff1 to your computer and use it in GitHub Desktop.
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.
"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