Astro性能优化Skill perf-astro

Astro性能优化技能,专注于通过关键CSS内联、文件压缩、字体加载和LCP优化等手段,提高Astro框架网站的Lighthouse评分至95分以上,适用于前端性能优化。关键词:Astro, 性能优化, Lighthouse, CSS内联, 压缩, 字体加载, LCP优化。

前端开发 0 次安装 0 次浏览 更新于 3/15/2026

name: perf-astro description: “Astro特定的性能优化,旨在达到95分以上的Lighthouse评分。涵盖关键CSS内联、压缩、字体加载和LCP优化。触发词:astro性能、astro lighthouse、astro优化、astro-critters。”

Astro性能优化指南

Astro特定的优化,旨在达到95分以上的Lighthouse评分。

快速设置

npm install astro-critters @playform/compress
// astro.config.mjs
import { defineConfig } from 'astro/config';
import critters from 'astro-critters';
import compress from '@playform/compress';

export default defineConfig({
  integrations: [
    critters(),
    compress({
      CSS: true,
      HTML: true,
      JavaScript: true,
      Image: false,
      SVG: false,
    }),
  ],
});

集成

astro-critters

自动提取并内联关键CSS。无需配置。

它的作用:

  • 扫描渲染的HTML以查找首屏元素
  • 仅内联这些元素所需的CSS
  • 延迟加载其余部分

构建输出显示内联的内容:

Inlined 40.70 kB (80% of original 50.50 kB) of _astro/index.xxx.css.

@playform/compress

在最终构建中压缩HTML、CSS和JavaScript。

选项:

compress({
  CSS: true,      // 压缩CSS
  HTML: true,     // 压缩HTML
  JavaScript: true, // 压缩JS
  Image: false,   // 如果使用外部图像优化,则跳过
  SVG: false,     // 如果SVG已优化,则跳过
})

布局模式

为性能构建您的Layout.astro

---
import '../styles/global.css'
---

<!doctype html>
<html lang="pt-BR">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!-- 字体后备(防止FOIT) -->
    <style>
      @font-face {
        font-family: 'Inter';
        font-display: swap;
        src: local('Inter');
      }
    </style>

    <!-- 非阻塞的Google字体 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap"
      media="print"
      onload="this.media='all'"
    />
    <noscript>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap">
    </noscript>

    <!-- 预加载LCP图像 -->
    <link rel="preload" as="image" href="/hero.png" fetchpriority="high">

    <title>{title}</title>

    <!-- 延迟第三方脚本 -->
    <script>
      let loaded = false;
      function loadAnalytics() {
        if (loaded) return;
        loaded = true;
        // 加载GTM、分析等
      }
      ['scroll', 'click', 'touchstart'].forEach(e => {
        document.addEventListener(e, loadAnalytics, { once: true, passive: true });
      });
      setTimeout(loadAnalytics, 5000);
    </script>
  </head>
  <body>
    <slot />
  </body>
</html>

测量

npx lighthouse https://your-site.com --preset=perf --form-factor=mobile

另请参阅:

  • perf-lighthouse - 运行审计、阅读报告、设置预算
  • perf-web-optimization - 核心Web Vitals、包大小、缓存策略

检查清单

  • [ ] 安装并配置astro-critters
  • [ ] 安装并配置@playform/compress
  • [ ] Google字体使用media="print" onload模式
  • [ ] 第三方脚本延迟到用户交互
  • [ ] LCP图像在<head>中预加载