Performance optimization: How to use Lighthouse to identify the culprits slowing down your page?
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:
- 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.
- Largest Contentful Paint (LCP): Measures when the largest content element visible in the viewport finishes rendering.
- Speed Index (SI): Measures how quickly the page content is visually displayed.
- Total Blocking Time (TBT): Measures the time the main thread is blocked, preventing the page from responding to user input.
- 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:
- Open Chrome Developer Tools (F12).
- Switch to the Lighthouse tab.
- Select the desired categories (Performance, PWA, etc.).
- 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:
-
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>
-
Unused JavaScript
// Use code splitting to dynamically load non-critical JS import('./module.js').then(module => { module.init(); });
-
Excessive DOM Elements
<!-- Simplify complex DOM structures --> <div class="card"> <h3>Product Title</h3> <p>Short Description</p> </div>
-
Uncompressed Resources
# Use Brotli compression Accept-Encoding: br
Optimizing the Critical Rendering Path
Optimizing the critical rendering path can significantly improve FCP and LCP:
-
Inline Critical CSS
<style> /* Inline critical CSS directly */ .header { color: #333; } </style>
-
Defer Non-Critical JS
<script src="non-critical.js" defer></script>
-
Preload Critical Resources
<link rel="preload" href="font.woff2" as="font" crossorigin>
-
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:
-
Code Splitting
// Dynamic imports const module = await import('./heavyModule.js');
-
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); };
-
Avoid Long Tasks
// Break long tasks into chunks function processInChunks() { setTimeout(() => { // Process a portion of data if (hasMore) processInChunks(); }, 0); }
-
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:
-
Avoid @import
/* Bad */ @import url('other.css'); /* Good */ <link rel="stylesheet" href="styles.css">
-
Use will-change
.animate { will-change: transform; }
-
Minimize Reflows
// Batch DOM operations const fragment = document.createDocumentFragment(); items.forEach(item => { const el = document.createElement('div'); fragment.appendChild(el); }); container.appendChild(fragment);
-
Use the contain Property
.isolated-component { contain: layout paint; }
Network Optimization Strategies
Network requests are critical to loading performance:
-
HTTP/2 Server Push
# nginx configuration http2_push /style.css; http2_push /app.js;
-
Resource Hints
<link rel="preconnect" href="https://cdn.example.com"> <link rel="dns-prefetch" href="https://cdn.example.com">
-
Smart Caching Policies
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires 1y; add_header Cache-Control "public, immutable"; }
-
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:
-
Set Performance Budgets
// package.json "performanceBudget": { "resources": [ { "resourceType": "script", "budget": 100 } ] }
-
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
-
Real User Monitoring (RUM)
// Use Navigation Timing API const [pageNav] = performance.getEntriesByType("navigation"); console.log('LCP:', pageNav.loadEventEnd);
-
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:
-
Edge Computing
// Cloudflare Workers example addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) })
-
Adaptive Loading
if (navigator.connection.effectiveType === '4g') { loadHighResImages(); } else { loadLowResImages(); }
-
WebAssembly Optimization
// Load WASM module WebAssembly.instantiateStreaming(fetch('module.wasm'), imports) .then(obj => obj.instance.exports.foo());
-
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