Lighthouse高分指南

85 阅读2分钟

一、核心指标深度优化

1. LCP(最大内容绘制)优化

  • 优化策略

    <!-- 关键图片预加载 -->
    <link rel="preload" href="hero-image.webp" as="image">
    
    <!-- 关键CSS内联 -->
    <style>
      /* 首屏关键样式 */
      .hero-section { ... }
    </style>
    
    <!-- 字体预加载 -->
    <link rel="preload" href="font.woff2" as="font" crossorigin>
    
  • 效果验证

    // 监听LCP指标
    new PerformanceObserver(entryList => {
      const entries = entryList.getEntries();
      const lastEntry = entries[entries.length - 1];
      console.log('LCP:', lastEntry.renderTime || lastEntry.loadTime);
    }).observe({type: 'largest-contentful-paint', buffered: true});
    

    2. CLS(累积布局偏移)消除

  • 实战方案

    /* 媒体元素尺寸约束 */
    img, video, iframe { 
      width: 100%;
      height: auto;
      aspect-ratio: attr(width) / attr(height);
    }
    
    /* 广告容器预留空间 */
    .ad-container {
      min-height: 300px;
      background: #f5f5f5;
    }
    
  • 动态内容处理

    // 动态加载内容前预留空间
    const placeholder = document.createElement('div');
    placeholder.style.height = '500px';
    document.body.appendChild(placeholder);
    
    fetchDynamicContent().then(content => {
      placeholder.replaceWith(content);
    });
    

    二、关键性能优化技术

1. 资源加载优化矩阵

技术手段实现方式Lighthouse影响
Brotli压缩Nginx配置:gzip on; brotli on; brotli_types text/plain application/json提升10-15%压缩率
新一代图片格式<picture><source srcset="image.avif" type="image/avif">...</picture>减少30-50%图片体积
代码分割vite.config.js: build.rollupOptions.output.manualChunks首屏JS减少40-60%
关键请求链优化preconnect、dns-prefetch预解析节省100-300ms

2. 渲染性能优化

  • GPU加速策略

    .animate-element {
      transform: translateZ(0);
      will-change: transform, opacity;
      contain: strict;
    }
    
  • 滚动性能优化

    // 虚拟滚动实现
    const visibleData = computed(() => 
      data.value.slice(
        Math.floor(scrollY.value / itemHeight),
        Math.floor((scrollY.value + viewportHeight) / itemHeight)
      )
    );
    

三、可访问性(Accessibility)提升

1. ARIA增强实践

<!-- 自定义复选框 -->
<div 
  role="checkbox"
  aria-checked="false"
  tabindex="0"
  @click="toggleCheckbox"
  @keydown.enter="toggleCheckbox"
>
  <span class="check-icon" :class="{checked: isChecked}"></span>
  {{ label }}
</div>

2. 焦点管理策略

// Vue指令实现焦点锁定
app.directive('focus-lock', {
  mounted(el) {
    const focusable = el.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    if (focusable.length) {
      focusable[0].focus();
    }
  }
});

四、SEO最佳实践

1. 结构化数据增强

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "Lighthouse优化指南",
  "author": {
    "@type": "Person",
    "name": "前端专家"
  },
  "datePublished": "2023-08-20"
}
</script>

2. 语义化HTML优化

<!-- 正确使用header/main/footer -->
<header aria-label="网站导航">
  <nav aria-label="主导航">
    <!-- 导航内容 -->
  </nav>
</header>

<main id="main-content" role="main">
  <article>
    <h1>主标题</h1>
    <section aria-labelledby="section1">
      <h2 id="section1">章节标题</h2>
      <!-- 内容 -->
    </section>
  </article>
</main>

五、持续优化工作流

1. 自动化监控方案

# GitHub Actions配置示例
name: Lighthouse Audit

on:
  schedule:
    - cron: '0 0 * * 1' # 每周一执行
  workflow_dispatch:

jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: treosh/lighthouse-ci-action@v9
        with:
          urls: |
            https://example.com/
            https://example.com/about
          budgetPath: ./lighthouse-budget.json

2. 性能预算配置

// lighthouse-budget.json
{
  "settings": {
    "budgets": [{
      "path": "/*",
      "resourceCounts": [
        { "resourceType": "script", "budget": 10 },
        { "resourceType": "image", "budget": 15 }
      ],
      "resourceSizes": [
        { "resourceType": "total", "budget": 500 }
      ]
    }]
  }
}

六、企业级优化案例

1. Next.js优化方案

// next.config.js
module.exports = {
  experimental: {
    optimizeCss: true,
    swcMinify: true,
    fontLoaders: [
      { loader: '@next/font/google', options: { subsets: ['latin'] } }
    ]
  },
  headers: async () => [
    {
      source: '/(.*)',
      headers: [
        { key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }
      ]
    }
  ]
}

2. CDN高级配置

# Nginx性能优化配置
server {
  gzip on;
  brotli on;
  brotli_types text/plain text/css application/json application/javascript;

  location ~* .(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    access_log off;
  }

  location / {
    add_header Content-Security-Policy "default-src 'self'";
    add_header X-Content-Type-Options "nosniff";
    add_header Strict-Transport-Security "max-age=63072000";
  }
}