Created
July 16, 2018 19:50
-
-
Save Yoplitein/81fe2223556198ad0085efb9d4d214a0 to your computer and use it in GitHub Desktop.
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
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