为什么 image 和 picture 元素显示图像尽管 http 状态为 404?

Why do image and picture elements display images despite http status 404?

以下请求 returns HTTP 状态代码 404,还有 content-type: image/jpeg 和响应正文中的有效 JPEG 数据:

https://img.youtube.com/vi/lXMskKTw3Bc/maxresdefault.jpg

如果您将此设置为图片的 src,该图片仍会显示。此外,未触发 onerror 事件,因此我无法使用 onerror="this.src=this.src.replace('maxres', 'sd')" 触发回退。

这种行为在 Firefox/Chrome/Edge 中是一致的,所以我想知道 1) 这是否是标准 中定义的内容?或者它实际上是所有主要浏览器中都存在的错误?

将其用作 picture 元素中的来源也不会使其回退到下一个可用图像大小并显示 "broken" 图像。

<h3>Plain image element:</h3>
<img src="https://img.youtube.com/vi/lXMskKTw3Bc/maxresdefault.jpg" onerror="this.src=this.src.replace('maxres', 'sd')">

<h3>Picture element:</h3>
<picture>
  <source media="(max-width: 640px)" srcset="https://img.youtube.com/vi/lXMskKTw3Bc/sddefault.jpg">
  <source media="(max-width: 480px)" srcset="https://img.youtube.com/vi/lXMskKTw3Bc/hqdefault.jpg">
  <source media="(max-width: 320px)" srcset="https://img.youtube.com/vi/lXMskKTw3Bc/mqdefault.jpg">
  <source srcset="https://img.youtube.com/vi/lXMskKTw3Bc/maxresdefault.jpg">
  <img src="https://img.youtube.com/vi/lXMskKTw3Bc/sddefault.jpg" type="image/jpeg">
</picture>

<h3>expected output:</h3>
<img src="https://img.youtube.com/vi/lXMskKTw3Bc/sddefault.jpg">

2) 有没有办法绕过这个问题并回退到不会导致 404 状态的下一个较小的图像尺寸,最好不使用 JavaScript?

感谢@Tyler Roper 的评论:

The documentation states that onerror is thrown when the image "fails to load". In your case, the image has loaded successfully; it's just accompanied by a 404 notifying you that it is not the image that you originally requested.

对于我的具体情况,我是这样解决的:

<img
  src="https://img.youtube.com/vi/lXMskKTw3Bc/maxresdefault.jpg"
  onload="if (this.naturalWidth < 1280) { this.src = this.src.replace('maxres', 'sd') }">

因此,它首先加载 maxresdefault,通常宽度至少应为 1280 像素。如果小于,则图片来源改为sddefault