How to Lazy Load Images in HTML for Faster Pages
To lazy load images in HTML, add the
loading="lazy" attribute to your <img> tags. This tells the browser to delay loading images until they are near the viewport, improving page speed and saving bandwidth.Syntax
The loading attribute on the <img> tag controls when the image loads.
loading="lazy": Defers loading the image until it is close to being visible.loading="eager": Loads the image immediately (default behavior).loading="auto": Lets the browser decide when to load.
html
<img src="image.jpg" alt="Description" loading="lazy">
Output
An image that loads only when near the screen
Example
This example shows two images: one lazy loaded and one loaded immediately. Scroll down to see the lazy loading in action.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lazy Load Images Example</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } img { display: block; margin-bottom: 40px; max-width: 100%; height: auto; } .spacer { height: 1000px; background: #f0f0f0; } </style> </head> <body> <h1>Lazy Load Images Demo</h1> <p>Image loaded immediately:</p> <img src="https://via.placeholder.com/600x300?text=Eager+Load" alt="Eager Load Image" loading="eager"> <div class="spacer">Scroll down to load the next image</div> <p>Image lazy loaded:</p> <img src="https://via.placeholder.com/600x300?text=Lazy+Load" alt="Lazy Load Image" loading="lazy"> </body> </html>
Output
A webpage with two images: the first loads immediately, the second loads only when scrolled near
Common Pitfalls
Common mistakes when lazy loading images include:
- Not adding
alttext, which hurts accessibility. - Using lazy loading on images that are immediately visible, causing a delay in showing important content.
- Relying on JavaScript libraries unnecessarily when native lazy loading is supported by modern browsers.
Always test on multiple browsers to ensure lazy loading works as expected.
html
<!-- Wrong: missing alt and lazy loading on above-the-fold image --> <img src="hero.jpg" loading="lazy" alt=""> <!-- Right: eager loading for above-the-fold image with alt text --> <img src="hero.jpg" alt="Hero image" loading="eager">
Quick Reference
Tips for using lazy loading effectively:
- Use
loading="lazy"on images below the fold. - Keep meaningful
alttext for accessibility. - Test on different devices and browsers.
- Combine lazy loading with responsive images (
srcset) for best performance.
Key Takeaways
Add
loading="lazy" to <img> tags to defer image loading until needed.Avoid lazy loading images that appear immediately on page load to prevent delays.
Always include descriptive
alt text for accessibility.Test lazy loading behavior across browsers and devices for consistent results.
Combine lazy loading with responsive images for optimal performance.