Sometimes, we want to preload images using JavaScript.
In this article, we’ll look at how to preload images using JavaScript.
Preload Images Using JavaScript
To preload images using JavaScript, we can create Image
instances for each image URL.
For instance, we can write:
const preload = (sources) => {
const images = [];
for (const s of sources) {
const image = new Image();
image.src = s
images.push(image)
}
}
preload([
'https://picsum.photos/id/0/5616/3744',
'https://picsum.photos/id/10/2500/1667'
])
to create the preload
function that takes the sources
array which has an array of image URLs.
In the function, we create the images
array to store the Image
instances.
Then we loop through the sources
with the for-of loop.
In the loop body, we create a new Image
instance.
And we set the src
property of it to the source
entry s
.
Finally, we call images.push
to add the entry to images
.
Conclusion
To preload images using JavaScript, we can create Image
instances for each image URL.