Middle
How to optimize image loading on a web page?
sobes.tech AI
Answer from AI
- Compression: Use tools to optimize image size without quality loss (e.g., TinyPNG, Compressor.io).
- Formats: Choose modern formats like WebP or AVIF, which provide better compression than JPEG and PNG. For older browsers, use
<picture>orsrcsetattribute for fallback. - Lazy Loading: Delay loading images outside the visible area until they are needed. Use native
loading="lazy"or JavaScript libraries. - Responsive Images: Serve different versions of images for various screen sizes and resolutions using
<picture>element orsrcset/sizesattributes. - CDN (Content Delivery Network): Host images on a CDN for faster content delivery to users from the nearest location.
- Caching: Set proper cache headers on the server so browsers can store images and load them from cache on repeat visits.
- Placeholder/Blurhash: Show a low-quality placeholder or generated Blurhash while the full-size image loads.
Example of using loading="lazy":
<img src="image.jpg" alt="Image description" loading="lazy">
Example of using <picture> for different formats:
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="Image description">
</picture>