In my slideshow, I initially load an image and trigger showImage() via onload. On clicking “Next,” I need to update the image’s src but ensure the loader is shown until the image finishes loading. How do I handle the dynamic image loading flow properly in javascript load image scenarios?
Instead of modifying the existing img tag, create a new Image() object in JavaScript and attach the onload logic:
function loadNewImage(newSrc) {
const loader = document.getElementById("loader");
const displayImage = document.getElementById("id1");
loader.style.display = "block"; // Show loader
displayImage.style.display = "none";
const img = new Image();
img.onload = function () {
displayImage.src = this.src;
loader.style.display = "none";
displayImage.style.display = "block";
};
img.src = newSrc;
}
This ensures the image only updates after it’s fully loaded.
To just add on what @vindhya.rddy said there is another effective approach is to dynamically update the <img> tag’s onload handler when changing the image source.
This allows you to show a loader while the new image is loading:
function updateImageSrc(newSrc) {
const image = document.getElementById("id1");
const loader = document.getElementById("loader");
loader.style.display = "block";
image.style.display = "none";
image.onload = function () {
loader.style.display = "none";
image.style.display = "block";
};
image.src = newSrc;
}
This method is clean and efficient; it reuses the same image element and dynamically attaches an onload handler to handle loading behavior every time the source changes.
Great for smooth UI transitions! Happy to help ![]()
If you’re already using jQuery in your project and want a cleaner way to handle image loading, this method might feel more intuitive. You can directly attach a .on("load") event like this:
function changeImage(newSrc) {
const $img = $("#id1");
$("#loader").show();
$img.hide();
$img.off("load").on("load", function () {
$("#loader").hide();
$(this).show();
}).attr("src", newSrc);
}
This makes sure you’re not stacking old onload handlers and keeps the logic neat, perfect for jQuery-based workflows.