I have been searching (unsuccessfully) for a reliable method to lazy load images while using the HTML5 spec for <picture>
. Most solutions/plugins out there currently rely on using data-
attributes. I could be wrong, but it doesn't seem this method will work in conjunction w/ <picture>
.
I'm really just looking to be pointed in the right direction. If anyone has a solution that they're currently using, I'd love to see. Thanks!
Here is standard markup per the HTML5 spec:
<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>
It's February 2020 now I'm pleased to report that Google Chrome, Microsoft Edge (the Chromium-based Edge), and Mozilla Firefox all support the new loading="lazy"
attribute. The only modern browser hold-out is Apple's Safari (both iOS Safari and macOS Safari) but they've recently finished adding it to Safari's codebase, so I expect it will be released sometime this year.
The loading="lazy"
attribute is only for the <img />
element (and not <picture>
) but remember that the <picture>
element does not represent the actual replaced-content, the <img />
element does (i.e. the image that users see is always rendered by the <img />
element, the <picture>
element just means that the browser can change the <img src="" />
attribute. From the HTML5 spec as of February 2020 (emphasis mine):
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.
So doing this should just-work:
<picture width="500" height="500">
<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>