I have a webpage which displays a large number of dynamic images (100+) in a masonry format via Bootstrap 4. Currently, my function waits until all images are loaded before rending the page.
I am fetching the list of image assets with getImages() and then adding them to the webpage dynamically with addElements(). Here is my code:
const init = async () => {
// get image URLs from backend service - returns a list of images files
const getImages = async () => {
let res = await fetch('/refresh', {method: 'POST'})
res = await res.json()
return res.data
}
// dynamic add images to webpage
const addElements = async () => {
const container = document.getElementById('content')
const data = await getImages()
for (let [index, image] of data.entries()) {
let card = document.createElement('div')
let img = document.createElement('img')
img.setAttribute('src', image.path)
card.appendChild(img)
container.appendChild(card)
}
}
await addElements()
}
window.onload = init
Since the order of the images on the webpage does not matter, I would like the images to appear on the page as soon as they are loaded, whereas currently no images appear on the page until addElements() returns. I'm assuming my current unwanted behavior has to do with the await addElements(), but I am confused on how to resolve the issue. Is it possible to render/add each image to the page as soon as it is loaded? How can I modify my example to accomplish this?