Astro Performance: เทคนิคทำให้เว็บเร็วระดับ 100/100
#astro12 เม.ย. 2569
ทำไม Astro ถึงเร็ว
Astro ออกแบบมาเพื่อ performance ตั้งแต่ต้น ด้วยหลักการ Zero JS by default
1. Image Optimization
---
import { Image, Picture } from 'astro:assets';
import heroImg from '../assets/hero.jpg';
---
<!-- Automatic optimization -->
<Image
src={heroImg}
alt="Hero"
width={800}
height={400}
format="webp"
quality={80}
loading="lazy"
/>
<!-- Responsive images -->
<Picture
src={heroImg}
formats={['avif', 'webp']}
alt="Hero"
widths={[400, 800, 1200]}
/>
2. Font Optimization
---
import { Font } from 'astro:assets';
---
<head>
<!-- Preload critical fonts -->
<Font family="Sarabun" preload />
</head>
3. Prefetch
---
import { prefetch } from 'astro:prefetch';
---
<!-- Prefetch เมื่อ hover -->
<a href="/about" data-astro-prefetch>เกี่ยวกับ</a>
<!-- Prefetch ทันที -->
<a href="/popular" data-astro-prefetch="load">บทความยอดนิยม</a>
4. Partytown สำหรับ Third-party Scripts
npx astro add partytown
<!-- รัน Google Analytics ใน Web Worker -->
<script type="text/partytown" src="https://www.googletagmanager.com/gtag/js"></script>
5. CSS Scoping
<style>
/* CSS นี้ scoped เฉพาะ component นี้ -->
/* ไม่มี global pollution -->
h1 { color: red; }
</style>
<style is:global>
/* Global CSS -->
body { margin: 0; }
</style>
6. Inline Critical CSS
<style is:inline>
/* CSS นี้จะ inline ใน HTML -->
.hero { background: #ff5d01; }
</style>
7. Compress Output
// astro.config.mjs
export default defineConfig({
compressHTML: true, // default true
build: {
inlineStylesheets: 'auto' // inline CSS เล็กๆ
}
});
Lighthouse Score
Astro default:
- Performance: 100
- Accessibility: 100
- Best Practices: 100
- SEO: 100
สรุป
Astro ให้ performance ที่ดีมากโดย default แค่ใช้ Image component และหลีกเลี่ยง client:load ที่ไม่จำเป็น ก็ได้ Lighthouse 100 ได้ไม่ยากครับ