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!
UPDATE:
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>
For anyone still interested... After revisiting this issue, I came across a fairly new script called, Lazysizes. It's actually quite versatile, but more importantly it allows me to do lazy loading of images while utilizing the HTML5 markup as described in the OP.
Much thanks to the creator of this script, @aFarkas.
Working example of lazy loading images using the picture element and intersection observer tested in Chrome and Firefox. Safari doesn't support intersection observer so the images are loaded immediately, and IE11 doesn't support the element so we fallback to the default img
The media queries in the media attr are arbitrary and can be set to suit.
The width threshold set is 960px - try a reload above and below this width to see either the medium(-m) or large(-l) variation of the image being downloaded when the image is scrolled into the viewport.
Codepen
and the JS:
One last thought is that if you change the screen width back and forth, the image files are repeatedly downloaded again. If I could tie the above method in to a cache check then this would be golden...