Skip to content

Instantly share code, notes, and snippets.

@ryanw3b3r
Created May 14, 2024 21:43
Show Gist options
  • Save ryanw3b3r/d0024f07a7c3585d57cdab0143643e4e to your computer and use it in GitHub Desktop.
Save ryanw3b3r/d0024f07a7c3585d57cdab0143643e4e to your computer and use it in GitHub Desktop.
Preload images in pure Javascript
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