Skip to content

Instantly share code, notes, and snippets.

@awsr
Created August 9, 2023 00:09
Show Gist options
  • Save awsr/b4fc356788c178cc4ac9a8c7ff775661 to your computer and use it in GitHub Desktop.
Save awsr/b4fc356788c178cc4ac9a8c7ff775661 to your computer and use it in GitHub Desktop.
Simple JavaScript function for preloading images
/**
* A function to preload images into the browser cache
*
* @param {string[]} imagePaths - Links to images you want to preload.
*
* @example
* const images = [
* "/relative/path/preload-me.png",
* "https://github.githubassets.com/images/modules/site/home/globe.jpg",
* "https://about.google/assets-main/img/glue-google-color-logo.svg"
* ];
* preloadImages(images);
*
*/
function preloadImages(imagePaths) {
const img = new Image();
const iterator = imagePaths.values();
img.addEventListener('load', () => {
const entry = iterator.next();
if (!entry.done) {
img.src = entry.value;
}
});
img.src = iterator.next().value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment