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.
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>