Lazy-Loading Images
You can use HTML's loading attribute on the img element to lazy-load images. This tells the browser to wait until the user scrolls near the image before downloading its file.
Lazy-loading is a technique that can significantly improve your website's performance, especially on pages with many images. By only loading images when they are actually needed, you can save bandwidth and speed up the initial page load time.
The Basic Syntax
To lazy-load an image, simply add loading="lazy" to your img tag:
Attribute Values
lazy: This is used to delay the loading of the image until it reaches a calculated distance from the viewport.eager: This is the default value. It tells the browser to load the image immediately, regardless of where it is on the page.
Interactive Example
Below is a working example of lazy-loading in action:
In the preview window, the second image only downloads once you scroll close to it. This help keep the initial page size smaller and faster to load.
Bear in mind that, although we're "lazy loading" the image, it will usually appear before the user scrolls to it. If it didn't, the image would only start downloading once the user scrolled to it, which would be a poor user experience (especially if the user scrolls through the document quickly). The browser will therefore start downloading the image once it's close to the viewport. Because of this, you might not notice any difference in the way the image loads. To see the difference, you can open your browser's network tab to see the difference in the way the images load.
Why Not Lazy-Load Everything?
You should generally avoid lazy-loading images that are likely to be visible in the user's viewport as soon as the page loads (the "above the fold" images). For those images, using loading="eager" (or just omitting the loading attribute) ensures they appear as quickly as possible. Lazy-load images that are further down the page to provide the best balance of performance and user experience.