Images Native Lazy Loading And Its Polyfill
Islam Sayed
Posted on September 1, 2019
What is Lazy loading
Images, and videos consume a huge amount of data, and affects web performances. If your web page contains many images (or videos), it is true that some -if not many- of them are out of viewport. The normal behaviour of any browser is to load all images during the web page loading which may slow loading time.
Lazy loading is used to defer images loading until it is about to enter the viewport, and only load the ones that are displayed once the web page loads. Thus decreases the time the web page needs to firstly load.
Native Lazy Loading
Developers use javascript plugins to make lazy loading. The good news is that Native lazy loading is now supported in Chrome 75. Using it is very simple. You will only have to add the attribute loading="lazy"
to the <img>
element.
<img src="image.jpg" loading="lazy" alt="..." />
The value of the attribute loading
can be either:
- lazy => tell the browser to load image just before showing onthe screen.
- eager => make browser load image as soon as possible. This can be added to the images that will appear inside viewport once theweb page loads.
- auto => make browser determine whether or not to lazily load.
Lazy Loading Plugin
There are many javascript plugins to achieve lazy loading. They depend on replacing src
attribute by data-src
attribute to prevent the browser from loading the image.
<img data-src="image.jpg" alt="..." />
Then use javascript to detect when image is close to the viewport to copy the value of the data-src
attribute to the src
attribute so the browser can load it.
Examples for such libraries:
Hybrid Lazy Loading
As explained by Andrea Verlicchi in his article on Smashing Magazine:
"Hybrid lazy loading is a technique to use native lazy loading on browsers that support it, otherwise, rely on JavaScript to handle the lazy loading."
<!--Load this hero image as soon as possible-->
<img src="hero.jpg" loading="eager" alt=".."/>
<!--Lazy load these images as user scroll down-->
<img data-src="image1.jpg" loading="lazy" alt=".." class="lazyload"/>
<img data-src="image2.jpg" loading="lazy" alt=".." class="lazyload"/>
<img data-src="image3.jpg" loading="lazy" alt=".." class="lazyload"/>
//Check for browser support.
if ('loading' in HTMLImageElement.prototype) {
const images = document.querySelectorAll('lazyload')
//copy the value of the data-src to the src.
images.forEach(img => img.src = img.dataset.src)
} else {
//if no support, async load the lazysizes plugin
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);
}
Resources
Posted on September 1, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.