Several posts on Stack Overflow (async/await
and here) offer solutions for loading images using JavaScript and executing callbacks once loaded.
Below is a modified version of the async/await
function from the first link, where the img
object/element is passed directly in the resolved promise for a loaded image.
async function loadImages(urlArr) {
// Array to hold promises
const promiseArr = [];
// Iterate through the URLs in the array
urlArr.forEach(url => {
promiseArr.push(new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener("load", () => resolve(img));
img.addEventListener("error", () => reject(img));
img.src = url;
}));
});
return await Promise.all(promiseArr);
}
After all images are loaded, iterate through the array of img
elements returned by Promise.all()
.
Note that a 404 error results in a resolved promise instead of rejected. To filter out img
elements with 404 responses:
const failedImages = images.filter(img => img.width <= 1);
if (failedImages.length > 0) {
failedImages.forEach(img => {
console.log(`The image ${img.src} failed to load.`);
});
return;
}
If all images load successfully, use a listener to trigger the display of the second ad image:
const transitionendListener = () => {
sidebarAdEl.classList.add("show");
bannerAdEl.removeEventListener("transitionend", transitionendListener);
};
bannerAdEl.addEventListener("transitionend", transitionendListener);
bannerAdEl.classList.add("show");
To see this in action, here's a sample implementation:
// Implementation code here
// CSS code here
<div class="sample">
<p>Sample content</p>
</div>