乐闻世界logo
搜索文章和话题

Astro 有哪些性能优化策略?如何构建超快速的 Astro 网站?

2月21日 16:15

Astro 提供了多种性能优化策略和技术,帮助开发者构建超快速的网站。了解这些优化技巧对于构建高性能的 Astro 应用至关重要。

核心性能优化策略:

  1. 零 JavaScript 默认

    • Astro 默认只输出纯 HTML
    • 只在需要时才加载 JavaScript
    • 显著减少初始加载时间
  2. 岛屿架构优化

    • 只为交互式组件添加 client:* 指令
    • 使用合适的 client:* 指令类型
    • 延迟非关键交互的水合

代码分割和懒加载:

astro
--- // 延迟加载组件 import { lazy } from 'astro'; const HeavyComponent = lazy(() => import('../components/HeavyComponent.jsx')); --- <HeavyComponent client:visible />

图片优化:

astro
--- import { Image } from 'astro:assets'; import heroImage from '../assets/hero.jpg'; --- <!-- 使用正确的格式和尺寸 --> <Image src={heroImage} alt="Hero" widths={[400, 800, 1200, 1600]} sizes="(max-width: 768px) 100vw, 50vw" formats={['avif', 'webp', 'jpeg']} loading="eager" priority={true} /> <!-- 懒加载非关键图片 --> <Image src={image} alt="Gallery Image" loading="lazy" decoding="async" />

CSS 优化:

astro
--- // 使用作用域样式 --- <style> /* 作用域样式,不会影响其他组件 */ .container { max-width: 1200px; margin: 0 auto; } </style> <style is:global> /* 全局样式,谨慎使用 */ body { font-family: system-ui, sans-serif; } </style>

预加载关键资源:

astro
--- // src/layouts/Layout.astro --- <html> <head> <!-- 预加载关键 CSS --> <link rel="preload" href="/styles/critical.css" as="style" /> <!-- 预加载字体 --> <link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin /> <!-- 预连接到外部域名 --> <link rel="preconnect" href="https://api.example.com" /> <!-- DNS 预解析 --> <link rel="dns-prefetch" href="https://cdn.example.com" /> </head> <body> <slot /> </body> </html>

数据获取优化:

astro
--- // src/pages/blog/[slug].astro import { getEntry } from 'astro:content'; // 并行获取数据 const [post, relatedPosts, comments] = await Promise.all([ getEntry('blog', Astro.params.slug), fetchRelatedPosts(Astro.params.slug), fetchComments(Astro.params.slug), ]); // 使用缓存 const cachedData = await cache.get(`post:${Astro.params.slug}`); if (cachedData) { return cachedData; } const data = await fetchData(); await cache.set(`post:${Astro.params.slug}`, data, { ttl: 3600 }); --- <h1>{post.data.title}</h1> <Content />

构建优化:

javascript
// astro.config.mjs import { defineConfig } from 'astro/config'; export default defineConfig({ build: { // 优化构建输出 inlineStylesheets: 'auto', }, vite: { build: { // 代码分割 rollupOptions: { output: { manualChunks: { vendor: ['react', 'react-dom'], utils: ['lodash', 'date-fns'], }, }, }, }, }, });

服务端渲染优化:

typescript
// src/middleware.ts export const onRequest = async (context, next) => { // 添加缓存头 const response = await next(); // 为静态资源添加长期缓存 if (context.url.pathname.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg)$/)) { response.headers.set('Cache-Control', 'public, max-age=31536000, immutable'); } // 为 API 响应添加短期缓存 if (context.url.pathname.startsWith('/api/')) { response.headers.set('Cache-Control', 'public, max-age=60'); } return response; };

使用适配器优化部署:

javascript
// astro.config.mjs import { defineConfig } from 'astro/config'; import vercel from '@astrojs/vercel/server'; export default defineConfig({ output: 'server', adapter: vercel({ // Vercel 特定优化 imageService: true, edgeMiddleware: true, }), });

性能监控和分析:

typescript
// src/lib/performance.ts export function measurePerformance(name: string, fn: () => Promise<void>) { return async () => { const start = performance.now(); await fn(); const duration = performance.now() - start; console.log(`${name} took ${duration.toFixed(2)}ms`); }; } // 使用 export async function GET(context) { await measurePerformance('data-fetch', async () => { const data = await fetchData(); return new Response(JSON.stringify(data)); }); }

Web Vitals 优化:

astro
--- // src/layouts/Layout.astro --- <html> <head> <script> // 监控 Core Web Vitals import { onCLS, onFID, onFCP, onLCP, onTTFB } from 'web-vitals'; onCLS(console.log); onFID(console.log); onFCP(console.log); onLCP(console.log); onTTFB(console.log); </script> </head> <body> <slot /> </body> </html>

减少第三方脚本:

astro
--- // 延迟加载分析脚本 --- <script> // 只在生产环境加载 if (import.meta.env.PROD) { window.addEventListener('load', () => { const script = document.createElement('script'); script.src = 'https://analytics.example.com/script.js'; script.async = true; document.head.appendChild(script); }); } </script>

使用 Service Worker 缓存:

typescript
// public/sw.js const CACHE_NAME = 'astro-v1'; const urlsToCache = ['/', '/styles/main.css']; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => cache.addAll(urlsToCache)) ); }); self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => response || fetch(event.request)) ); });
astro
--- // 注册 Service Worker --- <script> if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/sw.js'); }); } </script>

性能优化清单:

  1. 构建时优化

    • 启用代码分割
    • 压缩和优化资源
    • 使用 Tree Shaking
    • 优化图片和字体
  2. 运行时优化

    • 使用合适的 client:* 指令
    • 实现懒加载
    • 优化数据获取
    • 使用缓存策略
  3. 网络优化

    • 使用 CDN
    • 启用压缩(gzip、brotli)
    • 优化 HTTP 请求
    • 使用 HTTP/2 或 HTTP/3
  4. 渲染优化

    • 减少重绘和回流
    • 使用 CSS 动画而非 JavaScript
    • 优化 DOM 结构
    • 避免强制同步布局

性能测试工具:

  • Lighthouse
  • WebPageTest
  • Chrome DevTools Performance
  • Astro 内置的构建分析

Astro 的性能优化策略可以帮助你构建超快速的网站,提供优秀的用户体验和 SEO 表现。

标签:Astro