Back to All Questions
Question 79 of 100
Debugging
Advanced
How do you debug performance bottlenecks?
The Answer
Use Playwright Trace Viewer to analyze network waterfall charts, identify slow API calls, and see action timings. The `page.metrics()` API can capture Chrome performance metrics programmatically.
Deep Dive Explanation
The Trace Viewer's timeline view shows each network request, its duration, and when it was triggered relative to user actions. This makes it easy to spot slow API calls, unoptimized waterfalls, and render-blocking resources.
example.spec.ts
// Capture performance metrics
test('check page performance', async ({ page }) => {
await page.goto('/dashboard', { waitUntil: 'networkidle' });
const metrics = await page.evaluate(() =>
JSON.stringify(window.performance.getEntriesByType('navigation'))
);
const [navEntry] = JSON.parse(metrics);
console.log('DOMContentLoaded:', navEntry.domContentLoadedEventEnd);
console.log('Load time:', navEntry.loadEventEnd);
// Assert performance budget
expect(navEntry.loadEventEnd).toBeLessThan(3000); // Must load under 3s
});
// Enable tracing for network analysis
await context.tracing.start({ screenshots: true, snapshots: true });
await page.goto('/heavy-page');
await context.tracing.stop({ path: 'perf-trace.zip' });
// Open: npx playwright show-trace perf-trace.zip