Created
May 14, 2024 21:43
-
-
Save ryanw3b3r/d0024f07a7c3585d57cdab0143643e4e to your computer and use it in GitHub Desktop.
Preload images in pure Javascript
This file contains hidden or 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 preload = src => new Promise(function(resolve, reject) { | |
const img = new Image(); | |
img.onload = function() { | |
resolve(img); | |
} | |
img.onerror = reject; | |
img.src = src; | |
}); | |
const preloadAll = sources => | |
Promise.all( | |
sources.map( | |
preload)); | |
const sources = [ | |
'https://i.picsum.photos/id/1000/5626/3635.jpg', | |
'https://i.picsum.photos/id/10/2500/1667.jpg', | |
'https://homepages.cae.wisc.edu/~ece533/images/cat.png', | |
'https://homepages.cae.wisc.edu/~ece533/images/airplane.png']; | |
preloadAll(sources) | |
.then(images => console.log('Preloaded all', images)) | |
.catch(err => console.error('Failed', err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment