Search code examples
htmlimagehttp-status-code-404

<img>: force display of alt text on 404


Consider a trivial HTML file:

<html lang="en"><body>
<img src="https://thumbs.dreamstime.com/b/qqqqq.jpg" alt="ERROR"><br>
<img src="https://iili.io/qqqqq.jpg" alt="ERROR"><br>
</body></html>

Both images do not exist.

For the first image, the server returns a 404 with no content, and the browser displays the "ERROR" alt text as intended.

However, for the second image, the server returns a 404 status

enter image description here

but also sends content

404

and the image in the content is shown rather than the alt text.

Is there a way to force the alt text to be shown if the status indicates an error even if an image was sent in the content?

(I also tried using onerror but it isn't triggered in such cases.)


Solution

  • If the server returns a 404 status code and sends an image as the response content, the onload event will still be triggered for the <img> element. The onerror event will not be triggered in this case because the browser successfully loaded an image resource, even though it may not be the expected image.

    I can think of two possible solutions for this situation:

    • Server-side solution: Instead of directly requesting the images from "https://thumbs.dreamstime.com/b/qqqqq.jpg" or "https://iili.io/qqqqq.jpg", you can set up your own server. Modify the image response content on the server-side before sending it to the client. This way, you can control the behavior of the image and handle the error condition appropriately.

    • Client-side solution: In the onload event handler, you can check the loaded image and compare it with the error image. For example:

      <img src="https://thumbs.dreamstime.com/b/qqqqq.jpg" alt="ERROR" onload="handleLoad(this)" id="img1"><br>
      <img src="https://iili.io/qqqqq.jpg" alt="ERROR" onload="handleLoad(this)" id="img2"><br>
      
      function handleLoad(ele) {
        //simple comparison or use 3rd library for deep comparisons
        if (ele.width == 160 && ele.height == 160) {
          ele.src = "error";
        }
      }