Is there a cross-browser method for testing if an <img> tag is broken that doesn't require an inline event handler?

45 Views Asked by At

I am looking for a way to test whether the src of an image is broken, so that I can replace the src with a default image. However, I cannot use inline event handlers such as "onerror".

Does anyone know a way around this that wouldn't create incompatibility across browsers?

I have tried using a javascript event handler for the 'error' event, but it isn't triggering. I assume this is because the error event is firing before the javascript event listener has been placed on the img, but I can't say for certain.

EDIT: I believe I might just found something that could give a clue as to why the error event was not firing. The image file in question does exist on the server, but is an empty file. In short, the request is valid but the image file itself is broken. Would the valid request cause the image to not fire off an error event even if the image received was not valid? If so, is there a way to check if this has happened?

1

There are 1 best solutions below

2
MikO On

I made a quick and minimal mockup for the solution you said you tried, because i could not believe it to not work.

I tested it in Vivaldi, Chrome, Firefox and Safari and it worked like it should. Maybe you can elaborate, if you did something different to my example.

I just attached the error EventListener to the img element, which gets called when the image could not be loaded.

  const fallbackImage = "https://images.unsplash.com/photo-1699190375905-3cac33bbdbb1";
  const image = document.querySelector("#img");

  image.addEventListener("error", event => {
    console.log(`image could not be loaded, setting 'fallbackImage'...`);
    event.target.src = fallbackImage;
  });
img {
    max-width: 100%;
}
<!DOCTYPE html>
<html>

  <img src="https://images.unsplash.com/photo-1683009427051-00a2fe827a2c_" id=img />