img有onerror事件,理论上图片加载失败时会触发这个事件,但最近我测试遇到了没触发的场景,分析后发现这里有细节点要注意。
例子

# 不会触发onerror事件
<img src="https://i.postimg.cc/76vzQ3fQ/C01.jpg" onerror="alert(111)" />
# 会触发onerror事件
<img src="C01.jpg" onerror="alert(111)" />
如上图的图片请求返回时404状态码,但还是会返回图片格式的内容,因此并不会触发onerror事件。所以可以得出结论onerror并不看状态码,而是看是不是个正确的图片格式内容。
MDN关于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.
所以MDN的描述也说明了onerror事件是根据图片是否能正确加载来触发的,而不是根据HTTP状态码来判断的。
结论
onerror只能用于兜底图片本身无法加载的情况,如果服务本身返回了一个404状态码但内容是个正确的图片格式,那么onerror事件是不会被触发的。因此在使用onerror事件时需要注意这一点。如果确实需要根据HTTP状态码来判断图片是否加载成功,可能需要使用其他方法,比如通过JavaScript的fetch API先请求图片资源,检查状态码后再决定是否设置img的src属性。