Measuring Browser Performance with Headless Browsers
In this article
Measuring browser performance with headless browsers lets you automate page-load speed, JavaScript execution, and resource usage checks without opening a visible window. This is useful for CI/CD pipelines, regression testing, and comparing page versions. You'll get objective metrics like time-to-first-byte, largest contentful paint, and total page weight. Before starting, you need a basic understanding of the command line and a project directory to work in.
What You'll Need
- Node.js (version 14 or later) installed on your machine
- A code editor (like VS Code) or a text editor
- Google Chrome or Chromium browser installed (headless mode is built in)
- A terminal or command prompt
- Basic familiarity with JavaScript and npm
Step-by-Step
- Set up a new project. Create a new folder for your performance tests and open it in your terminal. Run
npm init -yto create apackage.jsonfile. - Install Puppeteer. Puppeteer is a Node.js library that controls headless Chrome. Run
npm install puppeteer. This will download a compatible version of Chromium automatically (unless you setPUPPETEER_SKIP_DOWNLOAD). - Write a basic script. Create a file named
measure.js. Start with a simple script that launches a headless browser, opens a page, and waits for it to load: - Capture performance metrics. Use the built-in
page.metrics()method to get low-level timing data. Also, use the Performance API to get navigation timing. Example code: - Measure Core Web Vitals. For modern metrics like LCP and CLS, use the
web-vitalslibrary. Install it withnpm install web-vitals, then inject it into the page. Example: - Take a performance trace. Use
page.tracing.start()andpage.tracing.stop()to generate a JSON trace file. This file can be opened in Chrome DevTools (via the Performance tab) for detailed analysis. - Run the script. Execute
node measure.jsin your terminal. The script will output the metrics to the console or save them to a file. - Automate multiple URLs. Loop through an array of URLs to test multiple pages. Ensure you wait for network idle before capturing metrics to avoid incomplete loads.
- Add a simple report. Format the results as JSON and write them to a file using
fs.writeFileSync. This makes it easy to compare runs over time.
Common Mistakes
- Not waiting for network idle. If you measure too early, metrics will be incomplete. Use
waitUntil: 'networkidle0'ornetworkidle2. - Ignoring browser warm-up. The first run of a headless browser may be slower due to caching. Run a few warm-up iterations before collecting final data.
- Measuring on a slow machine. Headless browsers on shared CI servers can produce inconsistent results. Use the same hardware or a dedicated runner for reliable comparisons.
- Not clearing cache between tests. If you want to measure cold loads, clear the cache or use a new incognito context for each run.
- Forgetting to close the browser. Always call
browser.close()to free memory, especially in loops.
Tips
- Use
page.setViewport()to simulate a mobile device. Mobile performance differs significantly from desktop. - Set a realistic network throttle. Use
page.setBypassCSP()andpage.setCacheEnabled(false)to simulate a slower connection if needed. - Take screenshots at key points. Visual regression can complement performance metrics.
- Use
--no-sandboxflag if running as root in CI. Some Linux environments require this to avoid sandbox errors. - Compare against a baseline. Store results from a known good version and compare new runs to detect regressions.
Troubleshooting
- Browser fails to launch. If you get an error about missing dependencies, run
npx puppeteer browsers install chromeor install system libraries listed in Puppeteer's troubleshooting docs. - Metrics are all zero. This often happens if you call
page.metrics()before the page is fully loaded. Ensure you awaitpage.goto()with proper wait conditions. - Script hangs. Add a timeout to
page.goto()(e.g.,timeout: 30000) and wrap it in a try-catch to handle slow pages. - Web-vitals not defined. Make sure you inject the library correctly. Use
page.addScriptTag({path: require.resolve('web-vitals')})or use the CDN version. - Memory usage spikes. If you're testing many pages, close each page after measuring with
page.close().
Frequently Asked Questions
Can I use headless Firefox instead of Chrome?
Yes, but Puppeteer is Chrome-specific. For Firefox, you can use Playwright, which supports both. The principles are the same.
How do I measure TTFB (Time to First Byte)?
Use the Performance API: performance.getEntriesByType('navigation')[0].responseStart. This gives the time from request start to first byte.
What's the difference between page.metrics() and the Performance API?
page.metrics() returns Chrome-specific internal counters like task duration and JS heap size. The Performance API provides standard web timing metrics like DOMContentLoaded and load events.
Can I measure performance on a real device?
Headless browsers simulate a desktop or mobile viewport but don't have real CPU/GPU. For real-device metrics, use tools like Lighthouse CI or WebPageTest.
Do I need to install a separate browser?
Puppeteer downloads a compatible Chromium version automatically. If you prefer to use an existing Chrome installation, set executablePath in the launch options.
How can I run these tests in CI?
Create a script in package.json that runs your measurement script. Use a CI service like GitHub Actions and cache the Puppeteer browser to speed up installs.