Search code examples
javascriptpagespeedastrojsimage-optimization

How to optimise a large image with Astro?


I am trying to optimise a 2.4 MB image (4514x5789) with Astro.

I tried:

<Image
  src={Image}
  alt="image"
  quality={80}
  format="webp"
  loading="lazy"
  widths={[390, Image.width]}
  sizes={`(max-width: 768) 390px, ${Image.width}px`}
  class="rounded-lg"
/>

Unfortunately this is not enough according to PageSpeed Insights. What can I change to get a performance score of 100?


Solution

  • According to the Astro docs, the widths attribute you're providing will be used to generate the srcset in HTML.

    Here's what that looks like on your page:

    <img
      src="/_vercel/image?url=_astro%2Fdaniell.ewbYQu3K.jpg&amp;w=3840&amp;q=80" 
      alt="Daniell sitting"
      loading="lazy"
      widths="390,4514"
      sizes="(max-width: 768) 390px, 4514px"
      class="rounded-lg"
      width="4514"
      height="5789"
      decoding="async">
    

    It seems the problem is that you're passing the width of the original image as one of the potential sizes for the srcset. On devices smaller than 768px, the 390px version of the image will be used. On devices wider than 768px, the full 4514px image will be used instead.

    It also seems that the largest the image could actually render on the page is 390px, so you don't need any sources larger than that. To fix the issue, try removing Image.width from widths and sizes:

    <Image
      src={Image}
      alt="image"
      quality={80}
      format="webp"
      loading="lazy"
      widths={[390]}
      sizes="390px"
      class="rounded-lg"
    />