Behold! Intersection Observers at work!
First, update your source code to move your image sources in to data attributes.
<!-- Image tags get `src` -->
<img data-src="foo/bar.png" alt="Foo Bar Image" />
<noscript>
<img src="foo/bar.png" alt="Foo Bar Image" />
</noscript>
<!-- Picture tags get `srcset` and `src` -->
<picture>
<source data-srcset="foo/bar.webp" type="image/webp">
<source data-srcset="foo/bar.png" type="image/png">
<img data-src="foo/bar.png" alt="Foo Bar Image" />
</picture>
<noscript>
<picture>
<source srcset="foo/bar.webp" type="image/webp">
<source srcset="foo/bar.png" type="image/png">
<img src="foo/bar.png" alt="Foo Bar Image" />
</picture>
</noscript>Then, when your DOM is loaded, run the lazyload function!
document.addEventListener('DOMContentLoaded', () => {
lazyload();
});- Lazyload grabs all of the
pictureandimgtags - If
IntersectionObserverexists, use it to set up lazyloading! If not, just load all of the images in - When an image has at least
1pxin the viewport, it'll load the images in