Issue
I'm wanting to show a new image in an existing <img> tag. To accomplish this, I'm updating the src attribute via Javascript. However, after changing the src, the screen doesn't change to show the new image loading. Instead, it waits until the new image is fully downloaded, then swaps it in.
In reality, I'm setting the background-image of the <img> tag to the URL of the thumbnail of the image being loaded. The goal being to have a poor quality image in place that gets gradually replaced with the good quality version. However, since the new image doesn't appear while loading, all I get is the old photo sitting there until the new one suddenly appears.
A simplified example is below. To really see the effect, open your DevTools > Network and set throttling to something slow. Click on the image, then wait until it suddenly changes. This is happening in Firefox and Chrome, so I'm guessing it's by design.
Any ideas how to bypass this behaviour?
const images = [
"https://picsum.photos/id/1/200/300",
"https://picsum.photos/id/2/200/300",
"https://picsum.photos/id/3/200/300",
"https://picsum.photos/id/4/200/300",
"https://picsum.photos/id/5/200/300"
];
let index = 0;
const length = images.length;
const img = document.querySelector("img");
document.addEventListener("click", e => {
index++;
img.src = images[index % length];
});
<img src = "https://picsum.photos/id/1/200/300" />
Solution
To make the current image disappear while the new image is loading, you need to remove its src attribute.
However for your <img> to have a size, you need to set it explicitly (here I've done it through CSS).
const images = [
"https://picsum.photos/id/1/200/300",
"https://picsum.photos/id/2/200/300",
"https://picsum.photos/id/3/200/300",
"https://picsum.photos/id/4/200/300",
"https://picsum.photos/id/5/200/300"
];
let index = 0;
const length = images.length;
const img = document.querySelector("img");
document.addEventListener("click", e => {
index++;
img.removeAttribute("src");
img.src = images[index % length];
});
img { background: red; width: 200px; height: 300px }
<img src = "https://picsum.photos/id/1/200/300" />
Answered By - Kaiido
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.