Astro Performance Optimization
Astro Performance Optimization
Section titled “Astro Performance Optimization”Astro đã nhanh theo mặc định, nhưng bạn có thể làm cho nó nhanh hơn nữa. Bài viết này tổng hợp các kỹ thuật optimization từ cơ bản đến nâng cao.
1. Islands Architecture
Section titled “1. Islands Architecture”Chọn đúng directive
Section titled “Chọn đúng directive”<!-- ❌ Không cần JS --><StaticContent />
<!-- ✅ Hydrate ngay --><InteractiveCounter client:load />
<!-- ✅ Hydrate khi browser idle --><Comments client:idle />
<!-- ✅ Hydrate khi visible --><Testimonials client:visible />
<!-- ✅ Hydrate ở màn hình nhỏ --><MobileMenu client:media="(max-width: 768px)" />
<!-- ✅ Chỉ client-side, không SSR --><Chart client:only="react" />2. Image Optimization
Section titled “2. Image Optimization”Astro Image component
Section titled “Astro Image component”---import { Image } from 'astro:assets';import myImage from '../assets/image.png';---
<!-- ✅ Tự động optimize --><Image src={myImage} alt="Description" width={800} height={400} format="webp"/>
<!-- ✅ Responsive images --><Image src={myImage} alt="Description" widths={[400, 800, 1200]} sizes="(max-width: 800px) 100vw, 800px"/>Lazy loading
Section titled “Lazy loading”<!-- Tự động lazy load --><Image src={myImage} alt="Description" loading="lazy" />
<!-- Eager load cho LCP image --><Image src={heroImage} alt="Hero" loading="eager" />External images
Section titled “External images”<!-- Dùng với external URLs --><img src="https://example.com/image.jpg" alt="Description" loading="lazy" decoding="async"/>3. Font Optimization
Section titled “3. Font Optimization”Font display swap
Section titled “Font display swap”/* ✅ Hiển thị text ngay, swap font sau */@font-face { font-family: 'Inter'; src: url('/fonts/Inter.woff2') format('woff2'); font-display: swap;}Preload critical fonts
Section titled “Preload critical fonts”<!-- Trong <head> --><link rel="preload" href="/fonts/Inter.woff2" as="font" type="font/woff2" crossorigin/>Subset fonts
Section titled “Subset fonts”# Chỉ include characters cần thiếtnpx glyphhanger https://yoursite.com \ --subset=/fonts/Inter.ttf \ --formats=woff24. CSS Optimization
Section titled “4. CSS Optimization”Purge unused CSS
Section titled “Purge unused CSS”import purgecss from 'astro-purgecss';
export default defineConfig({ integrations: [ purgecss({ safelist: ['dark', 'light'], // Classes không được purge }), ],});Critical CSS inline
Section titled “Critical CSS inline”---// Inline critical CSS---
<style is:inline> /* CSS cho Above-the-fold content */ .hero { /* ... */ } .navbar { /* ... */ }</style>
<!-- Non-critical CSS async --><link rel="preload" href="/styles/main.css" as="style" onload="this.onload=null;this.rel='stylesheet'">CSS tách biệt theo route
Section titled “CSS tách biệt theo route”---// Chỉ load CSS cho page nàyimport '../styles/blog.css';---5. Script Loading
Section titled “5. Script Loading”Async/Defer
Section titled “Async/Defer”<!-- ❌ Block rendering --><script src="/analytics.js"></script>
<!-- ✅ Load async --><script src="/analytics.js" async></script>
<!-- ✅ Execute sau khi parse xong --><script src="/analytics.js" defer></script>Dynamic import
Section titled “Dynamic import”<script> // Chỉ load khi cần document.querySelector('#load-map').addEventListener('click', async () => { const { initMap } = await import('./map.js'); initMap(); });</script>6. Build Optimization
Section titled “6. Build Optimization”Minify output
Section titled “Minify output”export default defineConfig({ build: { format: 'file', // Hash filenames for caching }, vite: { build: { minify: 'terser', terserOptions: { compress: { drop_console: true, // Xóa console.log }, }, }, },});Split chunks
Section titled “Split chunks”export default defineConfig({ vite: { build: { rollupOptions: { output: { manualChunks: { 'vendor': ['react', 'react-dom'], 'ui': ['./src/components/ui/index.js'], }, }, }, }, },});7. Caching Strategy
Section titled “7. Caching Strategy”HTTP Headers
Section titled “HTTP Headers”[[headers]] for = "/_astro/*" [headers.values] Cache-Control = "public, max-age=31536000, immutable"
[[headers]] for = "/images/*" [headers.values] Cache-Control = "public, max-age=2592000"Service Worker (advanced)
Section titled “Service Worker (advanced)”const CACHE_NAME = 'site-v1';
self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll([ '/', '/styles/main.css', '/scripts/app.js', ]); }) );});
self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => { return response || fetch(event.request); }) );});8. Prefetching
Section titled “8. Prefetching”Astro prefetch
Section titled “Astro prefetch”<!-- Prefetch on hover --><a href="/about" data-astro-prefetch>About</a>
<!-- Prefetch ngay --><a href="/blog" data-astro-prefetch="load">Blog</a>
<!-- Prefetch khi visible --><a href="/contact" data-astro-prefetch="viewport">Contact</a>import prefetch from '@astrojs/prefetch';
export default defineConfig({ integrations: [ prefetch({ selector: "a[href^='/']", throttle: 3, }), ],});9. Monitoring
Section titled “9. Monitoring”Lighthouse CI
Section titled “Lighthouse CI”name: Lighthouse CIon: [push]jobs: lighthouse: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - run: npm install - run: npm run build - uses: treosh/lighthouse-ci-action@v9 with: configPath: './lighthouserc.json'{ "ci": { "assert": { "assertions": { "categories:performance": ["error", { "minScore": 0.9 }], "categories:accessibility": ["error", { "minScore": 0.9 }], "categories:best-practices": ["error", { "minScore": 0.9 }], "categories:seo": ["error", { "minScore": 0.9 }] } } }}Web Vitals
Section titled “Web Vitals”<script> // Theo dõi Core Web Vitals new PerformanceObserver((list) => { for (const entry of list.getEntries()) { console.log('LCP:', entry.startTime); } }).observe({ entryTypes: ['largest-contentful-paint'] });</script>10. Common Pitfalls
Section titled “10. Common Pitfalls”Performance Checklist
Section titled “Performance Checklist”Trước launch
Section titled “Trước launch”- Lighthouse score 90+ (all categories)
- Core Web Vitals đạt chuẩn
- Images optimized (WebP/AVIF)
- Fonts subset và swap
- CSS minified và purged
- JS split và lazy loaded
- Caching headers configured
- Gzip/Brotli enabled
Tools hữu ích
Section titled “Tools hữu ích”| Tool | Mục đích |
|---|---|
| Lighthouse | Audit performance |
| WebPageTest | Test từ nhiều location |
| GTmetrix | Performance monitoring |
| Bundlephobia | Analyze package size |
| PurgeCSS | Remove unused CSS |