我一直在寻找(未成功)一种可靠的方法来延迟加载图像,同时使用 <picture>
的 HTML5 规范| .目前大多数解决方案/插件都依赖于使用 data-
属性。我可能是错的,但似乎这种方法不能与 <picture>
结合使用.
我真的只是希望找到正确的方向。如果有人有他们当前正在使用的解决方案,我很乐意看到。谢谢!
这是符合 HTML5 规范的标准标记:
<picture width="500" height="500">
<source media="(min-width: 45em)" src="large.jpg">
<source media="(min-width: 18em)" src="med.jpg">
<source src="small.jpg">
<img src="small.jpg" alt="">
</picture>
最佳答案
现在是 2020 年 2 月,我很高兴地报告 Google Chrome, Microsoft Edge (the Chromium-based Edge), and Mozilla Firefox全部支持新loading="lazy"
属性。唯一保留的现代浏览器是 Apple 的 Safari(iOS Safari 和 macOS Safari)but they've recently finished adding it to Safari's codebase ,所以我预计它会在今年某个时候发布。
loading="lazy"
属性仅适用于 <img />
元素(而不是 <picture>
),但请记住 <picture>
元素不代表实际的替换内容,<img />
元素确实如此(即用户看到的图像始终由 <img />
元素呈现,<picture>
元素仅意味着浏览器可以更改 <img src="" />
属性。From the HTML5 spec as of February 2020(强调我的):
The
picture
element is somewhat different from the similar-lookingvideo
andaudio
elements. While all of them containsource
elements, thesource
element'ssrc
attribute has no meaning when the element is nested within apicture
element, and the resource selection algorithm is different. Also, thepicture
element itself does not display anything; it merely provides a context for its containedimg
element that enables it to choose from multiple URLs.
所以这样做应该就可以:
<picture>
<source media="(min-width: 45em)" srcset="large.jpg" />
<source media="(min-width: 18em)" srcset="med.jpg" />
<source src="small.jpg" />
<img src="small.jpg" alt="Photo of a turboencabulator" loading="lazy" />
</picture>
请注意 the <picture>
element没有任何 width
或 height
自己的属性;而不是 width
和 height
属性应该应用于 child <source>
和 <img>
元素:
4.8.17 Dimension attributes
The
width
andheight
attributes onimg
,iframe
,embed
,object
,video
,source
when the parent is apicture
element [...] may be specified to give the dimensions of the visual content of the element (the width and height respectively, relative to the nominal direction of the output medium), in CSS pixels.[...]
The two attributes must be omitted if the resource in question does not have both an intrinsic width and an intrinsic height.
所以如果你想要所有<source>
要呈现为 500px
的图像通过 500px
然后将大小应用于 <img>
仅元素(并且不要忘记 alt=""
视觉障碍用户的文本,it's even a legal requirement in many cases ):
<picture>
<source media="(min-width: 45em)" srcset="large.jpg" />
<source media="(min-width: 18em)" srcset="med.jpg" />
<source src="small.jpg" />
<img src="small.jpg" alt="Photo of a turboencabulator" loading="lazy" width="500" height="500" />
</picture>
关于javascript - 延迟加载 HTML5 图片元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24025464/