Sometimes, we want to run code after all images have loaded with JavaScript.
In this article, we’ll look at how to run code after all images have loaded with JavaScript.
How to run code after all images have loaded with JavaScript?
To run code after all images have loaded with JavaScript, we can create a promise that resolves when all the images are loaded.
For instance, we write:
<img src='https://picsum.photos/200/300'>
<img src='https://picsum.photos/200'>
to add all images.
Then we write:
const imgLoadPromise = img => {
return new Promise(resolve => {
img.onload = () => {
resolve()
}
})
}
(async () => {
const promises = [...document.images]
.filter(img => !img.complete)
.map(imgLoadPromise)
await Promise.all(promises)
console.log('success')
})()
We create the imgLoadPromise
function that takes an img
element.
It returns a promise that resolves when img.onload
is run. When that’s run, the image is loaded successfully.
Then we create a promise that gets all the images with document.images
and spread them into an array.
Next, we call filter
with a callback to return with ones that haven’t loaded.
Then we call map
with imgLoadPromise
to map them to promises.
And then we call Promise.all
with promises
to wait for all of them to load.
Therefore, when all the images are loaded, 'success'
is logged in the console.
Conclusion
To run code after all images have loaded with JavaScript, we can create a promise that resolves when all the images are loaded.