DEV Community

saida lachgar
saida lachgar

Posted on • Originally published at saidalachgar.dev

Image Optimization in Astro: Boost Site Performance and SEO

Images are crucial for engagement but can slow down your website. Proper optimization improves load times, SEO rankings, and accessibility.

Storage Options

  • src/ directory: Use for automatic optimization (compression, resizing, format conversion)
  • public/ directory: Use for images that don't need processing or require direct URLs

Astro's Optimization Components

The <Image> Component

import { Image } from 'astro:assets';
import myImage from '../src/images/my-image.jpg';

<Image
  src={myImage}
  alt="Mountains at sunrise"
  width={800}
  height={600}
/>
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Automatic compression and WebP conversion
  • Required alt text for accessibility
  • Built-in lazy loading

The <Picture> Component

import { Picture } from 'astro:assets';
import myImage from '../src/images/my-image.jpg';

<Picture>
  <source srcset={myImage} type="image/webp" />
  <source srcset={myImage} type="image/jpeg" />
  <img src={myImage} alt="Mountains at sunrise" width={800} height={600} />
</Picture>
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Responsive design across devices
  • Multiple format support for browser compatibility

Best Practices

  • Choose appropriate formats (JPEG for photos, PNG for transparency, WebP for best compression)
  • Compress images to under 100KB when possible
  • Use descriptive alt text for accessibility and SEO
  • Take advantage of lazy loading
  • Always specify image dimensions to prevent layout shifts

Implementing these optimization techniques in Astro will significantly improve your site's performance, user experience, and search engine rankings.

For a deeper dive into optimizing Astro websites for SEO, including plugins and performance tips, check out my comprehensive guide.

Happy coding! 🚀

Top comments (0)