How to Lazy Load Images in HTML for Faster Web Pages
To lazy load an image in HTML, add the
loading="lazy" attribute to the <img> tag. This tells the browser to delay loading the image until it is near the viewport, improving page speed and saving bandwidth.Syntax
The loading attribute on the <img> tag controls when the image loads. Use loading="lazy" to enable lazy loading.
<img src="image.jpg" loading="lazy" alt="Description">- src: URL of the image
- loading: "lazy" delays loading until needed
- alt: text shown if image can't load, important for accessibility
html
<img src="image.jpg" loading="lazy" alt="Description">
Output
Displays the image but loads it only when near the screen.
Example
This example shows two images. The first loads immediately, the second uses lazy loading and loads only when you scroll near it.
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 Image Example</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } img { display: block; margin-bottom: 1000px; max-width: 100%; height: auto; } </style> </head> <body> <h1>Lazy Load Images Demo</h1> <p>Image 1 (loads immediately):</p> <img src="https://via.placeholder.com/400x200?text=Immediate+Load" alt="Immediate Load Image"> <p>Image 2 (lazy loaded): Scroll down to load</p> <img src="https://via.placeholder.com/400x200?text=Lazy+Loaded" loading="lazy" alt="Lazy Loaded Image"> </body> </html>
Output
Page with two images: first loads right away, second loads only when you scroll near it.
Common Pitfalls
Some common mistakes when using lazy loading:
- Forgetting the
loading="lazy"attribute means images load immediately. - Using lazy loading on very small or above-the-fold images can delay important content.
- Not providing
alttext hurts accessibility. - Older browsers may not support
loadingattribute; consider fallback or polyfill if needed.
html
<!-- Wrong: no lazy loading --> <img src="image.jpg" alt="No lazy loading"> <!-- Right: lazy loading added --> <img src="image.jpg" loading="lazy" alt="Lazy loading enabled">
Output
First image loads immediately, second image loads lazily.
Quick Reference
| Attribute | Description | Example |
|---|---|---|
| loading | Controls when image loads | ![]() |
| src | Image URL | ![]() |
| alt | Alternative text for accessibility | ![]() |
Key Takeaways
Add
loading="lazy" to <img> tags to enable lazy loading.Lazy loading delays image loading until near the viewport, improving page speed.
Always include meaningful
alt text for accessibility.Avoid lazy loading images that appear immediately on screen to prevent delays.
Check browser support; most modern browsers support
loading attribute natively.