blogbuituantuBùi Tuấn Tú

Tối ưu hiệu suất ảnh với Next.js

12 tháng 11, 2024

1. Chọn định dạng ảnh thông minh

js
// next.config.mjs
const nextConfig = {
  images: {
    formats: ["image/avif", "image/webp"],
  },
};
export default nextConfig;

2. Quản lý kích thước & layout

tsx
<div className="relative aspect-[16/9]">
  <Image
    src="/hero.png"
    alt="Demo"
    fill
    sizes="(max-width: 768px) 100vw, 768px"
    priority
  />
</div>

3. Lazy load & tính toán priority hợp lý

4. Tận dụng CDN & cache

5. Theo dõi bằng Lighthouse & WebPageTest

  1. Chạy Lighthouse trong DevTools, xem mục “Serve images in next-gen formats”.
  2. Dùng WebPageTest với tốc độ mạng 3G để đảm bảo LCP < 2.5s.
  3. Kết hợp next/script để defer script không cần thiết, giảm cạnh tranh bandwidth với ảnh.

Checklist cuối cùng