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

HTML <picture> — responsive image ที่ถูกวิธี

<picture> ให้ browser เลือก image ที่เหมาะสมที่สุดตาม viewport, format support และ DPR

<picture>
  <!-- WebP สำหรับ browser ที่รองรับ -->
  <source
    type="image/webp"
    srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
    sizes="(max-width: 600px) 100vw, 800px"
  />
  <!-- JPEG fallback -->
  <img
    src="hero-800.jpg"
    srcset="hero-400.jpg 400w, hero-800.jpg 800w"
    sizes="(max-width: 600px) 100vw, 800px"
    alt="Hero image"
    loading="lazy"
    decoding="async"
  />
</picture>

Art direction — เปลี่ยน crop ตาม viewport:

<picture>
  <source media="(max-width: 600px)" srcset="hero-square.jpg" />
  <source media="(min-width: 601px)" srcset="hero-wide.jpg" />
  <img src="hero-wide.jpg" alt="Hero" />
</picture>

sizes attribute สำคัญมาก: บอก browser ขนาดที่ image จะแสดง (CSS units) เพื่อให้เลือก source ที่ถูกต้องก่อน layout คำนวณเสร็จ

กฎง่ายๆ: ใช้ loading="lazy" ทุกรูปที่อยู่ใต้ fold, ใช้ loading="eager" สำหรับ LCP image