ข้ามไปเนื้อหาหลัก

Category: guide

Astro Image Optimization — ใช้ astro:assets ให้ถูกต้อง

คู่มือใช้ <Image /> component และ getImage() ใน Astro สำหรับ WebP, lazy loading และ responsive images ที่ optimize แล้ว

· อ่านประมาณ 1 นาที

สารบัญ

เปิดใช้ astro:assets

ตั้งแต่ Astro 3+ เปิดใช้งานได้เลยโดยไม่ต้อง config พิเศษ

---
import { Image } from 'astro:assets';
import heroImage from '../assets/hero.jpg';
---

<Image
  src={heroImage}
  alt="Hero image"
  width={800}
  height={400}
/>

Astro จะ:

  • แปลงเป็น WebP อัตโนมัติ
  • สร้าง srcset สำหรับ responsive
  • เพิ่ม loading="lazy" และ decoding="async" โดยอัตโนมัติ
  • ป้องกัน CLS ด้วยการ reserve space

Responsive Images

<Image
  src={heroImage}
  alt="Hero"
  widths={[400, 800, 1200]}
  sizes="(max-width: 600px) 100vw, (max-width: 1024px) 50vw, 800px"
  format="webp"
/>

LCP Image — ปิด lazy loading

<!-- สำหรับ above-fold image ที่เป็น LCP -->
<Image
  src={heroImage}
  alt="Hero"
  loading="eager"
  fetchpriority="high"
/>

Remote Images

---
// ต้องประกาศ domain ใน astro.config.mjs ก่อน
---
<Image
  src="https://example.com/photo.jpg"
  alt="Remote photo"
  width={600}
  height={400}
  inferSize   // Astro ดึง dimensions อัตโนมัติ
/>
// astro.config.mjs
export default defineConfig({
  image: {
    domains: ['example.com'],
  },
});

getImage() สำหรับ Background / OG

---
import { getImage } from 'astro:assets';
import ogImage from '../assets/og.jpg';

const optimized = await getImage({
  src: ogImage,
  width: 1200,
  height: 630,
  format: 'png',
});
---

<meta property="og:image" content={optimized.src} />

เมื่อไหร่ใช้ <img> ธรรมดา

  • SVG ที่ต้องการ preserve markup
  • Data URLs
  • รูปที่ generate ตอน runtime
  • รูปที่อยู่ใน public/ (ไม่ผ่าน optimization pipeline)
<!-- รูปใน public/ — ใช้ path string โดยตรง -->
<img src="/og-image.png" alt="OG" width="1200" height="630" />