How to Analyze Website Performance with Lighthouse: A Comprehensive Guide

If you‘re a web developer, you know that website performance is crucial for providing a good user experience and achieving strong search engine rankings. But how do you actually measure and optimize your site‘s performance? Enter Lighthouse, an open-source tool from Google that audits web pages and provides actionable feedback on how to improve their performance, accessibility, and more.

In this in-depth guide, we‘ll take a deep dive into Lighthouse from a full-stack developer‘s perspective. You‘ll learn how Lighthouse works under the hood, how to run audits in a variety of ways, what key metrics to focus on, and advanced techniques and tools for optimizing your scores. Let‘s get started!

What is Lighthouse and How Does It Work?

Lighthouse is an open-source, automated tool for improving the quality of web pages. It runs a series of audits on a web page, generating a report on how well the page did and providing suggestions for improvement.

Under the hood, Lighthouse uses the Chrome Remote Debugging Protocol to control a Chrome instance and gather performance metrics. It simulates a user visiting a page and records the page‘s activity as it loads.

Lighthouse audits fall into five main categories:

  1. Performance: Analyzes page load times and suggests ways to make pages load faster.
  2. Accessibility: Checks for common accessibility issues and suggests improvements to make pages more accessible.
  3. Best Practices: Looks for adherence to web development best practices.
  4. SEO: Verifies that pages are optimized for search engine results ranking.
  5. Progressive Web App: Checks if a page meets the core requirements for a progressive web app.

Each audit is scored on a scale of 0-100, with 0 being the worst and 100 being the best. These scores are then averaged into an overall score for each category.

Why Performance Matters

Before we dive into using Lighthouse, let‘s reinforce why performance is so critical with some hard data:

  • Pinterest increased search engine traffic and sign-ups by 15% when they reduced perceived wait times by 40%.
  • COOK increased conversions by 7%, decreased bounce rates by 7%, and increased pages per session by 10% when they reduced average page load time by 850 milliseconds.
  • BBC found they lost an additional 10% of users for every additional second their site took to load.
  • 53% of mobile site visits are abandoned if pages take longer than 3 seconds to load.

In short, faster pages lead to better user engagement, higher conversion rates, and improved search engine rankings. Performance isn‘t just a nice-to-have, it‘s a critical component of user experience and business success.

Running Lighthouse Audits

There are several ways to run a Lighthouse audit, each suited for different use cases. Let‘s look at each approach.

In Chrome DevTools

Running a Lighthouse audit in Chrome DevTools is the easiest way to get started. Here‘s how:

  1. In Chrome, go to the URL you want to audit.
  2. Open Chrome DevTools by pressing Command+Option+I (Mac) or Control+Shift+I (Windows, Linux, Chrome OS).
  3. Click the "Audits" tab.
  4. Choose the categories you want to audit and whether to simulate a mobile device.
  5. Click "Run audits".

DevTools will generate a report with scores for each category and specific suggestions for improvement.

From the Command Line

For integration into build processes or CI pipelines, you can run Lighthouse from the command line using its Node module. First, install Lighthouse as a global npm package:

npm install -g lighthouse

Then, run an audit on a URL:

lighthouse <url> --view

This will run the default Lighthouse audits and open the HTML report in your default browser. You can also specify options for the output format and location:

lighthouse <url> --output json --output-path ./lighthouse-results.json

In Continuous Integration

Integrating Lighthouse into your continuous integration pipeline allows you to catch performance regressions before they ship to users. Here‘s a basic approach:

  1. Install Lighthouse in your CI environment:

    npm install -g lighthouse
  2. Run Lighthouse and save the results as a JSON file:

    lighthouse <url> --output json --output-path ./lighthouse-results.json
  3. Use a tool like jq to extract the scores you care about from the JSON file and compare them to your performance budget:

    score=$(jq ‘.categories.performance.score‘ lighthouse-results.json)
    if (( $(echo "$score < 0.9" | bc -l) )); then
      echo "Lighthouse performance score is below threshold of 90."
      exit 1
    fi
  4. Fail the build if the scores don‘t meet your standards.

By integrating Lighthouse into your CI pipeline, you can ensure that performance remains a priority and catch issues before they impact users.

Tracking Performance Over Time

Monitoring Lighthouse scores over time gives you visibility into performance trends and the impact of your optimization efforts. Tools like Calibre and SpeedCurve can automatically run Lighthouse audits on a schedule, store the results, and provide dashboards and alerts on your performance metrics.

Here‘s an example of integrating Lighthouse audits with Calibre‘s API:

const fetch = require(‘node-fetch‘);
const lighthouse = require(‘lighthouse‘);
const chromeLauncher = require(‘chrome-launcher‘);

(async () => {
  const chrome = await chromeLauncher.launch({chromeFlags: [‘--headless‘]});
  const options = {
    logLevel: ‘info‘, 
    output: ‘json‘,
    onlyCategories: [‘performance‘],
    port: chrome.port,
  };

  const runnerResult = await lighthouse(‘https://example.com‘, options);
  const reportData = JSON.parse(runnerResult.report);

  const result = await fetch(‘https://api.calibreapp.com/metrics‘, {
    method: ‘POST‘,
    headers: { 
      ‘Content-Type‘: ‘application/json‘,
      ‘Authorization‘: `Bearer ${process.env.CALIBRE_API_KEY}`, 
    },
    body: JSON.stringify({
      site_slug: ‘example-com‘,
      timestamp: new Date().toISOString(),
      metrics: [
        {
          slug: ‘lighthouse-performance-score‘,
          value: reportData.categories.performance.score * 100,
        },
        // additional metrics here
      ],
    }),
  });

  console.log(‘Lighthouse scores sent to Calibre:‘, await result.json());

  await chrome.kill();
})();

This script launches a headless Chrome instance, runs a Lighthouse audit, and sends the performance score to Calibre‘s metrics API. Integrating a setup like this into your build process or running it on a scheduled basis with a tool like AWS Lambda can give you continuous visibility into your site‘s performance.

Key Lighthouse Metrics

While Lighthouse provides scores for many individual audits, there are a few key metrics that have an outsized impact on performance and user experience. Let‘s take a closer look at these metrics and how to optimize them.

First Contentful Paint (FCP)

First Contentful Paint measures how long it takes the browser to render the first piece of DOM content after a user navigates to your page. This could be text, an image, SVG, or even a <canvas> element.

To provide a good user experience, sites should strive to have an FCP of 1.8 seconds or less. Beyond 3 seconds, users perceive the delay and may start abandoning the site.

Some ways to improve FCP include:

  • Minimize the number of render-blocking resources
  • Minimize the number of server redirects
  • Use server-side rendering or prerendering
  • Inline critical CSS

Speed Index

Speed Index measures how quickly the contents of a page are visibly populated. It‘s calculated by comparing the visual progress of a page‘s load against the viewport at frequent intervals.

To provide a good user experience, sites should strive to have a Speed Index of less than 4.3 seconds. Beyond 5.8 seconds, users perceive the delay and may start abandoning the site.

Some ways to improve Speed Index include:

  • Optimize images (use appropriate formats, compress, resize)
  • Minify and compress text assets
  • Avoid enormous network payloads
  • Apply CSS styles as efficiently as possible

Time to Interactive (TTI)

Time to Interactive measures how long it takes a page to become fully interactive. A page is considered fully interactive when:

  • The page displays useful content (measured by FCP)
  • Event handlers are registered for most visible page elements
  • The page responds to user interactions within 50ms

To provide a good user experience, sites should strive to have a TTI of less than 5 seconds on mobile devices and less than 2 seconds on desktop.

Some ways to improve TTI include:

  • Minimize main thread work
  • Reduce JavaScript execution time
  • Minimize the depth of critical request chains
  • Use a web worker for long running tasks

Total Blocking Time (TBT)

Total Blocking Time measures the total amount of time between FCP and TTI where the main thread was blocked for long enough to prevent input responsiveness.

To provide a good user experience, sites should strive to have a TBT of less than 300 milliseconds. Beyond 600 milliseconds, users perceive the delay and may start abandoning the site.

Some ways to improve TBT include:

  • Break up Long Tasks
  • Optimize your page for interaction readiness
  • Use a web worker
  • Reduce JavaScript execution time

First Meaningful Paint (FMP)

First Meaningful Paint measures when the primary content of a page is visible. It‘s the paint after which the biggest above-the-fold layout change has happened and web fonts have loaded.

While FMP isn‘t an official Lighthouse metric, it‘s still an important milestone for users and can be a useful benchmark for your site. Sites should aim to have an FMP of 1 second or less on mobile devices.

Some ways to improve FMP include:

  • Prioritize loading content that‘s above the fold
  • Use server-side rendering or prerendering
  • Inline critical CSS
  • Avoid font-display:block

Time to First Byte (TTFB)

Time to First Byte measures the time between the browser requesting a page and when it receives the first byte of information from the server. It‘s impacted by server processing time, network latency, and caching.

To provide a good user experience, sites should strive to have a TTFB of less than 1.3 seconds. Beyond 2.5 seconds, users perceive the delay and may start abandoning the site.

Some ways to improve TTFB include:

  • Optimize your server‘s application logic
  • Use a CDN to serve static assets
  • Cache assets and API responses on the server
  • Enable HTTP/2

Advanced Performance Optimization Techniques

Once you‘ve addressed the basics of performance optimization, there are some more advanced techniques that can yield significant improvements. Here are a few to consider:

Implement Code Splitting

Code splitting is the practice of splitting your JavaScript bundles into smaller chunks and loading them on demand. This can significantly improve TTI and reduce TBT by reducing the amount of JavaScript that needs to be parsed and executed upfront.

There are several approaches to code splitting:

  • Route-based splitting: Split your bundles based on the routes or pages in your application
  • Component-based splitting: Split your bundles at the component level
  • Function-based splitting: Split your bundles based on specific functions or features

Popular tools like webpack and Rollup make code splitting relatively straightforward. Here‘s an example using webpack‘s dynamic imports:

import(‘./some-module.js‘)
  .then(module => {
    // Do something with the module.
  })
  .catch(error => {
    // Handle the error.
  });

Optimize the Critical Rendering Path

The critical rendering path is the sequence of steps the browser goes through to convert HTML, CSS, and JavaScript into pixels on the screen. Optimizing this path can significantly improve FCP and FMP.

Here are some techniques for optimizing the critical rendering path:

  • Minimize the number of critical resources: Eliminate unnecessary resources or defer their loading
  • Minimize the size of critical resources: Minify and compress CSS, JavaScript, and HTML
  • Optimize the order of critical resources: Load CSS before JavaScript and defer non-critical JavaScript
  • Use server-side rendering or prerendering: Generate HTML on the server or during a build step to reduce client-side rendering time

Tools like critical and penthouse can help automate the process of extracting and inlining critical CSS.

Implement a Service Worker

Service workers are scripts that run in the background, separate from a web page. They enable features like offline support, push notifications, and background syncing.

From a performance perspective, service workers can significantly improve repeat visit load times by caching assets and API responses. They can also enable offline functionality, which can improve perceived performance and user experience.

Here‘s a basic example of a service worker that caches static assets:

self.addEventListener(‘install‘, event => {
  event.waitUntil(
    caches.open(‘static-cache‘).then(cache => {
      return cache.addAll([
        ‘/‘,
        ‘/styles/main.css‘,
        ‘/scripts/main.js‘,
        ‘/images/logo.png‘,
      ]);
    })
  );
});

self.addEventListener(‘fetch‘, event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

This service worker caches the specified assets when it‘s installed and serves them from the cache when they‘re requested, falling back to the network if they‘re not cached.

Implementing a comprehensive caching strategy with a service worker can be complex, but tools like Workbox can help simplify common caching patterns.

Additional Resources and Tools

Performance optimization is a deep and ever-evolving field. Here are some additional resources and tools to help deepen your knowledge and streamline your optimization efforts:

Conclusion

In this guide, we‘ve taken a deep dive into analyzing web performance with Lighthouse. We‘ve covered how Lighthouse works, how to run audits in a variety of environments, key metrics to focus on, advanced optimization techniques, and additional resources for further learning.

As a full-stack developer, it‘s critical to prioritize performance and make it a core part of your development process. By regularly auditing your sites with Lighthouse, setting performance budgets, and continuously monitoring real-user metrics, you can ensure that you‘re delivering fast, engaging experiences to your users.

Performance optimization is a journey, not a destination. By staying up-to-date with the latest techniques and tools, and always keeping the user experience at the forefront, you can make sure your sites are fast, resilient, and successful.

Similar Posts