Skip to content

Instantly share code, notes, and snippets.

@Yoplitein
Created July 16, 2018 19:50
Show Gist options
  • Save Yoplitein/81fe2223556198ad0085efb9d4d214a0 to your computer and use it in GitHub Desktop.
Save Yoplitein/81fe2223556198ad0085efb9d4d214a0 to your computer and use it in GitHub Desktop.
const cache = {};
const queue = [];
export function enqueueImage(path)
{
if(cache.hasOwnProperty(path))
return;
queue.push(path);
}
export async function cacheImages()
{
const promises = [];
for(let path of queue)
{
const img = new Image();
img.src = path;
cache[path] = img;
promises.push(new Promise(resolve => img.addEventListener("load", resolve)));
}
for(let promise of promises)
await promise;
queue.length = 0;
}
export function getImage(path)
{
if(cache.hasOwnProperty(path))
return cache[path];
throw new Error(`Image at \`${path}\` is not cached!`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment