Lazy-loading is the simple process of loading resources only when they are needed. These resources can be anything, from images to stylesheets, fonts, scripts, iframes etc.
This helps improve the performance of your website drastically because client does not have to download the images, videos and other resources when they aren't required. 🥳🎈
We're going to use the package called, "Lozad." To lazy-load images. Lozad. will only add 1 KB to your production 📦! Check out Bundlephobia 😱 for more info.
We're only going to lazy-load images but Lozad can handle lazy-loading for srcsets, background images, videos and iframes too. So, let's include the package and start hacking! 🪓
npm i lozad
Include Lozad in your entry or main JavaScript file. Alternatively, you could use Lozad CDN if you don't have module bundler set up.
import lozad from 'lozad';
// Makes sure to run the library when DOM loads.
document.addEventListener('DOMContentLoaded', () => {
/**
* This is all you need to do!
* Check the link for advanced usages.
* https://www.npmjs.com/package/lozad
*/
lozad().observe();
});
By default, Lozad will look for elements with class, "lozad". When the element is about to enter the viewport, Lozad takes the data-src or other such Lozad related attributes and assigns it to the src attribute to load the image.
<img class="lozad" data-src="https://example.com/img.jpg" />
That's it, you've successfully added support for lazy-loading 🎉🧨🎊!
Best practice would be to leave the images that are in the header and lazy-load only the ones that are below the initial viewport.
Challenge!
Use Lozad to lazy-load a background image and video!
Thoughts?
Please, share your thoughts and experiences as to how lazy-loading improved your website. PS, are you guys interested in me writing about lazy-loading using vanilla JavaScript? Let me know in the comments, thank you!
Top comments (6)
Either way you can use :
The loading attribute on an element (or the loading attribute on an ) can be used to instruct the browser to defer loading of images/iframes that are off-screen until the user scrolls near them.
Source:
developer.mozilla.org/en-US/docs/W...
Thank you for sharing this! Yes, browsers natively support lazy-loading and they also natively support dynamic imports for scripts. The issue is browser compatibility and making sure that the site runs smoothly in case someone is using an older browser.
If supporting older browsers isn't a priority for you then the loading attribute you mention is a better choice. Please, look into support for the loading attribute here: caniuse.com/?search=lazy%20loading
good one!
Thank you Fogr, glad you liked it! :)
Combine this with proper srcset images and you got yourself a smoothly loading and performant web page. Thanks for the write up.
Yes! Lozad handles srcset which makes it an awesome solution.