Skip to content

Instantly share code, notes, and snippets.

@kerenren
Created September 27, 2021 13:06
Show Gist options
  • Save kerenren/9f4ed14bfd9431284634287fbd63ad67 to your computer and use it in GitHub Desktop.
Save kerenren/9f4ed14bfd9431284634287fbd63ad67 to your computer and use it in GitHub Desktop.
Preload images into caches in react
// exmpale to use Promise.all to preload all the iamges in the array to the app
// [loading, setLoading] = useState(false);
const cacheImages = async (srcArray) => {
const promises = await srcArray.map((src)=>{
return new Promise((resolve, reject) => {
const img = new Image();
img.src = src;
img.onload = resolve;
img.onerror = reject;
})
})
await Promise.all(promises)
// setLoading(false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment