The
imgelement has anonerrorevent, which in theory fires when an image fails to load. Recently, however, I ran into a case where it didn’t fire. After digging in, I found a subtle detail worth knowing.
Example

# Does NOT trigger onerror
<img src="https://i.postimg.cc/76vzQ3fQ/C01.jpg" onerror="alert(111)" />
# DOES trigger onerror
<img src="C01.jpg" onerror="alert(111)" />
In the example above, the image request returns a 404 status code, but the response body is still valid image content, so onerror does not fire. The conclusion: onerror doesn’t care about the HTTP status code — it only cares whether the response is a properly-formed image.
What MDN Says About onerror
If an error occurs while loading or rendering an image, and an onerror event handler has been set for the error event, that event handler will get called. This can happen in several situations, including:
- The src or srcset attributes are empty ("") or null.
- The src URL is the same as the URL of the page the user is currently on.
- The image is corrupted in some way that prevents it from being loaded.
- The image’s metadata is corrupted in such a way that it’s impossible to retrieve its dimensions, and no dimensions were specified in the
element’s attributes.
- The image is in a format not supported by the user agent.
So MDN confirms that onerror is triggered based on whether the image can be properly loaded — not based on the HTTP status code.
Conclusion
onerror only works as a fallback when the image itself cannot be loaded. If the server returns a 404 status code but the response body is still a valid image, onerror won’t fire. Keep this in mind when relying on onerror. If you really need to make decisions based on the HTTP status code, consider an alternative approach — for example, using fetch to request the image first, checking the status code, and only then setting the src attribute on the img element.

