Paulund

Optimizing Image Handling in HTML: A Comprehensive Guide to Best Practices

Use onerror

Use onerror as a fallback for src attribute.

<img src="https://example.com/image.png" onerror="this.src='https://example.com/placeholder.png'">

Use Background Color

Using a background color is a good practice for images that are not loaded yet.

img {
    background-color: #eee;
}

Use Lazy Loading

Lazy loading is a good practice for images that are not visible on the screen.

<img src="https://example.com/image.png" loading="lazy">

Use srcset

Use srcset to provide multiple image sources for different screen sizes.

<img src="https://example.com/image.png" srcset="https://example.com/image-2x.png 2x, https://example.com/image-3x.png 3x">

Use alt

Use alt attribute to provide a description for the image.

<img src="https://example.com/image.png" alt="Image description">

Use Aspect Ratio

Use Aspect Ratio to prevent layout shift.

img {
    aspect-ratio: 16/9;
}

Choose The Right Image Format

Make sure that you use the right image format for the type of image you want to display.

  • Use PNG for images with transparency.
  • Use JPEG for images with no transparency.
  • Use WebP for images with transparency and/or with animations.

WebP images will generally provide better comporession than older formats like PNG and JPEG.

You can use WebP images will another image format as a fallback.

<picture>
    <source srcset="https://example.com/image.webp" type="image/webp">
    <img src="https://example.com/image.png" alt="Image description">
</picture>