阿里云主机折上折
  • 微信号
Current Site:Index > Performance optimization: How to use Lighthouse to identify the culprits slowing down your page?

Performance optimization: How to use Lighthouse to identify the culprits slowing down your page?

Author:Chuan Chen 阅读数:44720人阅读 分类: 前端综合

What is Lighthouse

Lighthouse is an open-source automated tool developed by Google for improving web page quality. It can run as a Chrome extension or be used via the command line or as a Node module. Lighthouse performs a series of tests on a web page and generates reports on aspects such as page performance, accessibility, Progressive Web Apps (PWA), and more.

The easiest way to install Lighthouse is through the Chrome extension:

chrome://extensions/ -> Search for "Lighthouse" -> Add to Chrome

Alternatively, install it globally via npm:

npm install -g lighthouse

Performance Metrics Interpretation

The Lighthouse performance report includes several key metrics, each reflecting different aspects of page loading:

  1. First Contentful Paint (FCP): Measures the time from when the page starts loading until any part of the page content is rendered on the screen.
  2. Largest Contentful Paint (LCP): Measures when the largest content element visible in the viewport finishes rendering.
  3. Speed Index (SI): Measures how quickly the page content is visually displayed.
  4. Total Blocking Time (TBT): Measures the time the main thread is blocked, preventing the page from responding to user input.
  5. Cumulative Layout Shift (CLS): Measures the frequency of unexpected layout shifts during page loading.

For example, the LCP for an e-commerce site might be the main product image:

<!-- This is a typical LCP element -->
<img src="product-image.jpg" alt="Main product image" class="product-image">

Running Lighthouse Tests

There are multiple ways to run Lighthouse tests:

Via Chrome DevTools:

  1. Open Chrome Developer Tools (F12).
  2. Switch to the Lighthouse tab.
  3. Select the desired categories (Performance, PWA, etc.).
  4. Click "Generate Report."

Via Command Line:

lighthouse https://example.com --view --preset=desktop

Via Node.js API:

const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');

async function runLighthouse(url) {
  const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
  const options = {logLevel: 'info', output: 'html', port: chrome.port};
  const runnerResult = await lighthouse(url, options);
  
  // Output the report
  console.log('Performance score:', runnerResult.lhr.categories.performance.score * 100);
  
  await chrome.kill();
  return runnerResult.report;
}

Analyzing Performance Bottlenecks

After obtaining the Lighthouse report, focus on the "Opportunities" and "Diagnostics" sections:

Common performance issues include:

  1. Unoptimized Images

    // Use WebP format instead of JPEG/PNG
    <picture>
      <source srcset="image.webp" type="image/webp">
      <img src="image.jpg" alt="Example image">
    </picture>
    
  2. Unused JavaScript

    // Use code splitting to dynamically load non-critical JS
    import('./module.js').then(module => {
      module.init();
    });
    
  3. Excessive DOM Elements

    <!-- Simplify complex DOM structures -->
    <div class="card">
      <h3>Product Title</h3>
      <p>Short Description</p>
    </div>
    
  4. Uncompressed Resources

    # Use Brotli compression
    Accept-Encoding: br
    

Optimizing the Critical Rendering Path

Optimizing the critical rendering path can significantly improve FCP and LCP:

  1. Inline Critical CSS

    <style>
      /* Inline critical CSS directly */
      .header { color: #333; }
    </style>
    
  2. Defer Non-Critical JS

    <script src="non-critical.js" defer></script>
    
  3. Preload Critical Resources

    <link rel="preload" href="font.woff2" as="font" crossorigin>
    
  4. Use Server-Side Rendering (SSR)

    // Next.js example
    export async function getServerSideProps() {
      const data = await fetchData();
      return { props: { data } };
    }
    

Optimizing JavaScript Execution

JavaScript is a major cause of high TBT:

  1. Code Splitting

    // Dynamic imports
    const module = await import('./heavyModule.js');
    
  2. Use Web Workers for Heavy Tasks

    // main.js
    const worker = new Worker('worker.js');
    worker.postMessage(data);
    
    // worker.js
    onmessage = (e) => {
      const result = processData(e.data);
      postMessage(result);
    };
    
  3. Avoid Long Tasks

    // Break long tasks into chunks
    function processInChunks() {
      setTimeout(() => {
        // Process a portion of data
        if (hasMore) processInChunks();
      }, 0);
    }
    
  4. Optimize Event Handling

    // Use debouncing/throttling
    window.addEventListener('scroll', throttle(handleScroll, 200));
    

Optimizing CSS Performance

Poor CSS handling can cause layout thrashing and render blocking:

  1. Avoid @import

    /* Bad */
    @import url('other.css');
    
    /* Good */
    <link rel="stylesheet" href="styles.css">
    
  2. Use will-change

    .animate {
      will-change: transform;
    }
    
  3. Minimize Reflows

    // Batch DOM operations
    const fragment = document.createDocumentFragment();
    items.forEach(item => {
      const el = document.createElement('div');
      fragment.appendChild(el);
    });
    container.appendChild(fragment);
    
  4. Use the contain Property

    .isolated-component {
      contain: layout paint;
    }
    

Network Optimization Strategies

Network requests are critical to loading performance:

  1. HTTP/2 Server Push

    # nginx configuration
    http2_push /style.css;
    http2_push /app.js;
    
  2. Resource Hints

    <link rel="preconnect" href="https://cdn.example.com">
    <link rel="dns-prefetch" href="https://cdn.example.com">
    
  3. Smart Caching Policies

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

    <!-- Use multiple CDN domains for parallel loading -->
    <script src="https://cdn1.example.com/jquery.js"></script>
    <script src="https://cdn2.example.com/lodash.js"></script>
    

Monitoring and Continuous Optimization

Performance optimization is not a one-time task:

  1. Set Performance Budgets

    // package.json
    "performanceBudget": {
      "resources": [
        {
          "resourceType": "script",
          "budget": 100
        }
      ]
    }
    
  2. Integrate into CI/CD

    # GitHub Actions example
    - name: Run Lighthouse
      run: |
        npm install -g lighthouse
        lighthouse https://your-site.com --output=json --output-path=./lhreport.json
    
  3. Real User Monitoring (RUM)

    // Use Navigation Timing API
    const [pageNav] = performance.getEntriesByType("navigation");
    console.log('LCP:', pageNav.loadEventEnd);
    
  4. A/B Test Optimization Results

    // Use Google Optimize
    gtag('event', 'optimize.load', {
      'experiment_id': 'AbCdEfGhIjKlMnOpQrStUv',
      'variant': '0'
    });
    

Advanced Optimization Techniques

For scenarios requiring extreme performance:

  1. Edge Computing

    // Cloudflare Workers example
    addEventListener('fetch', event => {
      event.respondWith(handleRequest(event.request))
    })
    
  2. Adaptive Loading

    if (navigator.connection.effectiveType === '4g') {
      loadHighResImages();
    } else {
      loadLowResImages();
    }
    
  3. WebAssembly Optimization

    // Load WASM module
    WebAssembly.instantiateStreaming(fetch('module.wasm'), imports)
      .then(obj => obj.instance.exports.foo());
    
  4. Server Components

    // React Server Components
    import db from 'db'; 
    
    async function Note({id}) {
      const note = await db.posts.get(id);
      return <NoteView note={note} />;
    }
    

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.