Created
August 9, 2023 00:09
-
-
Save awsr/b4fc356788c178cc4ac9a8c7ff775661 to your computer and use it in GitHub Desktop.
Simple JavaScript function for preloading images
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
/** | |
* 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