AddyOsmani.com - Native image lazy-loading for the web! →
The
loadingattribute allows a browser to defer loading offscreen images and iframes until users scroll near them.loadingsupports three values:
- lazy: is a good candidate for lazy loading.
- eager: is not a good candidate for lazy loading. Load right away.
- auto: browser will determine whether or not to lazily load.
This is so cool! It's available in Chrome and easy to implement as an enhancement of current lazyloading strategies, e.g. paired with LazySizes as a fallback:
<img data-src='unicorn.jpg' loading='lazy' alt='..' class='lazyload'/>
<img data-src='cats.jpg' loading='lazy' alt='..' class='lazyload'/>
<img data-src='dogs.jpg' loading='lazy' alt='..' class='lazyload'/>
<script>
if ('loading' in HTMLImageElement.prototype) {
const images = document.querySelectorAll('img.lazyload');
images.forEach(img => {
img.src = img.dataset.src;
});
} else {
// Dynamically import the LazySizes library
let script = document.createElement('script');
script.async = true;
script.src =
'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/4.1.8/lazysizes.min.js';
document.body.appendChild(script);
}
</script>The future is now! 😁🚀