Sometimes, we want to make an image load synchronously with JavaScript.
In this article, we’ll look at how to make an image load synchronously with JavaScript.
How to make an image load synchronously with JavaScript?
To make an image load synchronously with JavaScript, we can make a promise that loads the image.
For instance, we write:
const loadImage = (url) => {
const img = new Image()
return new Promise(resolve => {
img.onload = () => {
resolve(img)
}
img.src = url
})
}
const urls = [
'https://i.picsum.photos/id/879/200/300.jpg?hmac=07llkorYxtpw0EwxaeqFKPC5woveWVLykQVnIOyiwd8',
'https://i.picsum.photos/id/35/200/300.jpg?hmac=No1hMogzX_PUqgWDfLRCc4wGPYTIeviBhJbzjqskoMA',
'https://i.picsum.photos/id/56/200/300.jpg?hmac=XmVgSk2B8hc9Smojh4o14JnHBHBM8Gj0ePS78sxZbzI'
]
const load = async () => {
for (const u of urls) {
const img = await loadImage(u)
document.body.appendChild(img)
}
}
load()
We define the loadImage
functino that returns a promise with the img element.
We create the img element with the Image
constructor.
And we call resolve
with img
once the image has been loaded by setting the img.src
to the image url
.
Next, we define the load
function that loops through each image URL in urls
and call loadImage
on each entry.
And then we call document.body.appendChild
with img
to add the image as a child of the body element.
Conclusion
To make an image load synchronously with JavaScript, we can make a promise that loads the image.