I have a program with dynamically updating images which I'm updating from a script, when it canat find an image, I want it to show a backup image. I've tried using this onerror="this.onerror=null;this.src=
piece of code in the html img tag, but it only works once and does not work once the img source is updated from the script. I am not sure how to work around this.
Asked
Active
Viewed 38 times
0

vvhitearmor
- 51
- 7
-
Does this answer your question? [Programmatically change the src of an img tag](https://stackoverflow.com/questions/11722400/programmatically-change-the-src-of-an-img-tag) – DevZer0 Nov 13 '21 at 05:32
-
@DevZer0 no this is just changing the the source of an image. I can already do that, but i want it to have a fallback image that loads when it is changed from the script. – vvhitearmor Nov 13 '21 at 05:44
-
i don't see the difference of what you are trying to do with the script other than setting the src attribute using a script – DevZer0 Nov 13 '21 at 06:07
-
Best practise is a server side implementation. If server is unable to send any image it must be programmed to send any alternate image. And speaking of the "img" tag in html it prints "alt" attribute when image is not loaded. So you can use it. – gaurav Nov 13 '21 at 06:28
1 Answers
0
As I commented above it should be server side implementation.
But I wrote a client side code for you.
You just need to add a "imgSrcArr" containing all the possible and alternate sources in a Array. And keep checking the dimension of the img element. If dimension is 0, just change the source.
<body>
<img src="null0" />
</body>
<script>
window.addEventListener("load", (event) => {
var image = document.querySelector("img");
var imgSrcArr = ["null1", "null2", "https://picsum.photos/200/300"];
let index = 0; // img index to be incremented
let thisInterval = setInterval(() => {
var isLoaded = image.complete && image.naturalHeight !== 0;
console.log("Checking Image => " + index);
if (isLoaded) {
// if image is loaded
console.log(isLoaded);
console.log("Image loaded :)");
clearInterval(thisInterval); // clearInterval
} else {
console.log("Changing img source=> " + index);
image.setAttribute("src", imgSrcArr[index]);
if (index <= imgSrcArr.length) {
index++;
}
}
}, 2000);
});
</script>

gaurav
- 491
- 3
- 13