This content originally appeared on DEV Community and was authored by Muhammad Hasnain
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.
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';
// Make sure to run the library only when all DOM elements are available.
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 images with class, "lozad," and the attribute of "data-src". When the image is about to enter the viewport, Lozad takes the data-src attribute and assigns it to 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!
This content originally appeared on DEV Community and was authored by Muhammad Hasnain
Muhammad Hasnain | Sciencx (2021-06-05T00:38:39+00:00) How to lazy-load images? The easiest way to lazy-load images on your website! ?. Retrieved from https://www.scien.cx/2021/06/05/how-to-lazy-load-images-the-easiest-way-to-lazy-load-images-on-your-website-%f0%9f%96%bc/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.