Measuring Front-End Performance with Selenium
Collect Navigation Timing, paint and LCP metrics with Selenium, throttle Chromium networks, run Lighthouse alongside tests, and assert performance budgets.
Your Selenium suite loads every important page of your application, many times a day, in a real browser. That makes it a free source of front-end performance data: how long the document took, when the first pixels appeared, when the largest content element rendered, how much JavaScript was downloaded. With a few lines of code per page you can turn “the dashboard feels slower this sprint” into a failing build with a number attached.
What a Selenium suite cannot do is tell you how the system behaves under load. That distinction comes first, because confusing the two is the most common performance-testing mistake teams make with Selenium.
Selenium Is Not a Load-Testing Tool
| Question | Right tool |
|---|---|
| How fast does this page render for one user, and did it get slower? | Selenium + browser performance APIs, Lighthouse |
| How many concurrent users can the backend handle before latency degrades? | k6, Gatling, JMeter, Locust (protocol-level load) |
| How does real-user performance look across devices and networks? | Real User Monitoring (RUM) via web-vitals in production |
Each Selenium session drives a full browser that needs hundreds of megabytes of RAM and a CPU core while rendering. A 16-core Grid node runs perhaps 8 to 16 sessions; generating 1,000 concurrent users would take a data centre and would mostly measure your Grid, not your application. Load tools issue HTTP requests directly and simulate thousands of users from one machine.
The useful combination: run a protocol-level load test against staging and, while it is running, a small Selenium check that measures front-end timings. That tells you what a real user experiences when the backend is busy.
The Browser Performance APIs
Browsers expose detailed timing data through the W3C Performance APIs. Selenium reads them with executeScript, so this works in every browser with no CDP, no extra libraries and through a Grid.
| Metric | API | What it tells you |
|---|---|---|
| TTFB (time to first byte) | PerformanceNavigationTiming.responseStart | Server and network latency for the HTML document |
| DOMContentLoaded | PerformanceNavigationTiming.domContentLoadedEventEnd | HTML parsed, deferred scripts run |
| Load | PerformanceNavigationTiming.loadEventEnd | All subresources loaded |
| First Contentful Paint | performance.getEntriesByType('paint') | First text or image painted |
| Largest Contentful Paint | PerformanceObserver type largest-contentful-paint | When the main content rendered (Core Web Vital) |
| Cumulative Layout Shift | PerformanceObserver type layout-shift | Visual stability (Core Web Vital) |
| Resource sizes and timings | performance.getEntriesByType('resource') | Per-request duration, transfer size |
LCP and CLS are Chromium-only APIs today (Firefox has added LCP in recent releases; Safari does not expose either). Navigation Timing, Paint Timing and Resource Timing work everywhere.
Navigation and paint timing
driver.get("https://app.example.com/dashboard");
@SuppressWarnings("unchecked")Map<String, Object> timing = (Map<String, Object>) ((JavascriptExecutor) driver).executeScript(""" const nav = performance.getEntriesByType('navigation')[0]; const fcp = performance.getEntriesByName('first-contentful-paint')[0]; return { ttfb: nav.responseStart, domContentLoaded: nav.domContentLoadedEventEnd, load: nav.loadEventEnd, transferSize: nav.transferSize, fcp: fcp ? fcp.startTime : null };""");
System.out.println(timing);double fcp = ((Number) timing.get("fcp")).doubleValue();assertTrue(fcp < 1800, "FCP " + fcp + "ms exceeds 1800ms budget");driver.get("https://app.example.com/dashboard")
timing = driver.execute_script(""" const nav = performance.getEntriesByType('navigation')[0]; const fcp = performance.getEntriesByName('first-contentful-paint')[0]; return { ttfb: nav.responseStart, domContentLoaded: nav.domContentLoadedEventEnd, load: nav.loadEventEnd, transferSize: nav.transferSize, fcp: fcp ? fcp.startTime : null };""")
print(timing)assert timing["fcp"] < 1800, f"FCP {timing['fcp']:.0f}ms exceeds 1800ms budget"await driver.get('https://app.example.com/dashboard');
const timing = await driver.executeScript(`const nav = performance.getEntriesByType('navigation')[0];const fcp = performance.getEntriesByName('first-contentful-paint')[0];return { ttfb: nav.responseStart, domContentLoaded: nav.domContentLoadedEventEnd, load: nav.loadEventEnd, transferSize: nav.transferSize, fcp: fcp ? fcp.startTime : null};`);
console.log(timing);assert.ok(timing.fcp < 1800, `FCP ${timing.fcp}ms exceeds 1800ms budget`);driver.Navigate().GoToUrl("https://app.example.com/dashboard");
var timing = (Dictionary<string, object>)((IJavaScriptExecutor)driver).ExecuteScript(@" const nav = performance.getEntriesByType('navigation')[0]; const fcp = performance.getEntriesByName('first-contentful-paint')[0]; return { ttfb: nav.responseStart, domContentLoaded: nav.domContentLoadedEventEnd, load: nav.loadEventEnd, transferSize: nav.transferSize, fcp: fcp ? fcp.startTime : null };");
var fcp = Convert.ToDouble(timing["fcp"]);Assert.That(fcp, Is.LessThan(1800), $"FCP {fcp}ms exceeds 1800ms budget");All values are milliseconds relative to performance.timeOrigin (the start of navigation). Read them after the page has finished loading: driver.get waits for the load event under the default page load strategy, so loadEventEnd is populated by the time the script runs. If you use the eager or none strategy, wait for document.readyState === 'complete' first; see Page Load Strategy and Timeouts.
Numbers come back as JSON numbers, which Java may map to Long or Double depending on whether there is a fractional part. Go through Number (Java) or Convert.ToDouble (C#) rather than casting to a specific type.
Largest Contentful Paint and layout shift
LCP entries are not available through getEntriesByType; they are delivered to a PerformanceObserver. With buffered: true, the observer receives entries that were recorded before it was created, so you can attach it after the page has loaded and still get the value.
private static final String WEB_VITALS = """ const done = arguments[arguments.length - 1]; let lcp = null, cls = 0; new PerformanceObserver(list => { const entries = list.getEntries(); lcp = entries[entries.length - 1].startTime; }).observe({ type: 'largest-contentful-paint', buffered: true }); new PerformanceObserver(list => { for (const e of list.getEntries()) if (!e.hadRecentInput) cls += e.value; }).observe({ type: 'layout-shift', buffered: true }); // Observers deliver buffered entries asynchronously; give them a frame or two setTimeout(() => done({ lcp, cls }), 250);""";
driver.get("https://app.example.com/products");@SuppressWarnings("unchecked")Map<String, Object> vitals = (Map<String, Object>) ((JavascriptExecutor) driver).executeAsyncScript(WEB_VITALS);
double lcp = ((Number) vitals.get("lcp")).doubleValue();double cls = ((Number) vitals.get("cls")).doubleValue();assertTrue(lcp < 2500, "LCP " + lcp + "ms");assertTrue(cls < 0.1, "CLS " + cls);WEB_VITALS = """const done = arguments[arguments.length - 1];let lcp = null, cls = 0;new PerformanceObserver(list => {const entries = list.getEntries();lcp = entries[entries.length - 1].startTime;}).observe({ type: 'largest-contentful-paint', buffered: true });new PerformanceObserver(list => {for (const e of list.getEntries()) if (!e.hadRecentInput) cls += e.value;}).observe({ type: 'layout-shift', buffered: true });setTimeout(() => done({ lcp, cls }), 250);"""
driver.get("https://app.example.com/products")vitals = driver.execute_async_script(WEB_VITALS)
assert vitals["lcp"] < 2500, f"LCP {vitals['lcp']:.0f}ms"assert vitals["cls"] < 0.1, f"CLS {vitals['cls']:.3f}"const WEB_VITALS = `const done = arguments[arguments.length - 1];let lcp = null, cls = 0;new PerformanceObserver(list => { const entries = list.getEntries(); lcp = entries[entries.length - 1].startTime;}).observe({ type: 'largest-contentful-paint', buffered: true });new PerformanceObserver(list => { for (const e of list.getEntries()) if (!e.hadRecentInput) cls += e.value;}).observe({ type: 'layout-shift', buffered: true });setTimeout(() => done({ lcp, cls }), 250);`;
await driver.get('https://app.example.com/products');const vitals = await driver.executeAsyncScript(WEB_VITALS);
assert.ok(vitals.lcp < 2500, `LCP ${vitals.lcp}ms`);assert.ok(vitals.cls < 0.1, `CLS ${vitals.cls}`);const string WebVitals = @" const done = arguments[arguments.length - 1]; let lcp = null, cls = 0; new PerformanceObserver(list => { const entries = list.getEntries(); lcp = entries[entries.length - 1].startTime; }).observe({ type: 'largest-contentful-paint', buffered: true }); new PerformanceObserver(list => { for (const e of list.getEntries()) if (!e.hadRecentInput) cls += e.value; }).observe({ type: 'layout-shift', buffered: true }); setTimeout(() => done({ lcp, cls }), 250);";
driver.Navigate().GoToUrl("https://app.example.com/products");var vitals = (Dictionary<string, object>)((IJavaScriptExecutor)driver).ExecuteAsyncScript(WebVitals);
Assert.That(Convert.ToDouble(vitals["lcp"]), Is.LessThan(2500));Assert.That(Convert.ToDouble(vitals["cls"]), Is.LessThan(0.1));Caveats that matter when you assert on these:
- LCP is finalised on first user input. Selenium clicks count as input. Measure LCP immediately after navigation, before interacting with the page.
- CLS accumulates over the page’s life. Measured at load, it only covers load-time shifts. That is usually what you want in a test, but it is not the same number field data reports.
- INP (Interaction to Next Paint) needs real interactions and the Event Timing API; Google’s
web-vitalslibrary computes it properly. For INP, injectweb-vitalswith a preload script or as part of your test build, and read the reported values fromwindow. - Headless and headed differ. Headless Chrome in a container has no GPU and usually a smaller CPU budget. Compare like with like; never compare a laptop number to a CI number.
Resource timing: catching heavy pages
Many performance regressions are not slow servers but bigger pages: a new analytics script, an unoptimised hero image, an accidental full-library import. Resource Timing reports every request and its transfer size.
@SuppressWarnings("unchecked")Map<String, Object> bytes = (Map<String, Object>) ((JavascriptExecutor) driver).executeScript(""" const totals = { script: 0, img: 0, css: 0, other: 0, count: 0 }; for (const r of performance.getEntriesByType('resource')) { const key = r.initiatorType === 'script' ? 'script' : r.initiatorType === 'img' ? 'img' : r.initiatorType === 'link' && r.name.endsWith('.css') ? 'css' : 'other'; totals[key] += r.transferSize; // 0 for cached or cross-origin without Timing-Allow-Origin totals.count++; } return totals;""");
long jsKb = ((Number) bytes.get("script")).longValue() / 1024;assertTrue(jsKb <= 350, "JavaScript transfer " + jsKb + " KB exceeds 350 KB budget");totals = driver.execute_script(""" const totals = { script: 0, img: 0, css: 0, other: 0, count: 0 }; for (const r of performance.getEntriesByType('resource')) { const key = r.initiatorType === 'script' ? 'script' : r.initiatorType === 'img' ? 'img' : r.initiatorType === 'link' && r.name.endsWith('.css') ? 'css' : 'other'; totals[key] += r.transferSize; totals.count++; } return totals;""")
js_kb = totals["script"] / 1024assert js_kb <= 350, f"JavaScript transfer {js_kb:.0f} KB exceeds 350 KB budget"const totals = await driver.executeScript(`const totals = { script: 0, img: 0, css: 0, other: 0, count: 0 };for (const r of performance.getEntriesByType('resource')) { const key = r.initiatorType === 'script' ? 'script' : r.initiatorType === 'img' ? 'img' : r.initiatorType === 'link' && r.name.endsWith('.css') ? 'css' : 'other'; totals[key] += r.transferSize; totals.count++;}return totals;`);
const jsKb = totals.script / 1024;assert.ok(jsKb <= 350, `JavaScript transfer ${jsKb.toFixed(0)} KB exceeds 350 KB budget`);var totals = (Dictionary<string, object>)((IJavaScriptExecutor)driver).ExecuteScript(@" const totals = { script: 0, img: 0, css: 0, other: 0, count: 0 }; for (const r of performance.getEntriesByType('resource')) { const key = r.initiatorType === 'script' ? 'script' : r.initiatorType === 'img' ? 'img' : r.initiatorType === 'link' && r.name.endsWith('.css') ? 'css' : 'other'; totals[key] += r.transferSize; totals.count++; } return totals;");
var jsKb = Convert.ToDouble(totals["script"]) / 1024;Assert.That(jsKb, Is.LessThanOrEqualTo(350), $"JavaScript transfer {jsKb:F0} KB exceeds 350 KB budget");Byte budgets are far more stable than time budgets: the same build downloads the same bytes on every run, regardless of CI machine load. Start with byte budgets and add time budgets once you have controlled the environment.
Note:
transferSizeis 0 for resources served from cache and for cross-origin resources without aTiming-Allow-Originheader. Run budget checks in a fresh session (Selenium gives you a clean profile by default) and expect third-party scripts to be under-counted.
For Chromium-specific counters (JS heap size, DOM node count, layout count), CDP’s Performance.getMetrics is covered in Chrome DevTools Protocol.
Network Throttling
On a gigabit office connection, every page is fast. Throttling shows you what a 4G user on a train sees, and exercises loading states that never appear otherwise. Chromium-based drivers expose a simple network-conditions API in every binding, with no version-specific CDP imports.
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
ChromeDriver chrome = (ChromeDriver) driver;ChromiumNetworkConditions slow = new ChromiumNetworkConditions();slow.setLatency(Duration.ofMillis(150));slow.setDownloadThroughput(1_600 * 1024 / 8); // bytes per second (~1.6 Mbps)slow.setUploadThroughput(750 * 1024 / 8);chrome.setNetworkConditions(slow);
driver.get("https://app.example.com/products");// ... measure, assert skeleton loaders appear, etc.
chrome.deleteNetworkConditions();driver.set_network_conditions( offline=False, latency=150, # ms download_throughput=1_600 * 1024 // 8, # bytes per second upload_throughput=750 * 1024 // 8,)
driver.get("https://app.example.com/products")# ... measure
driver.delete_network_conditions()await driver.setNetworkConditions({offline: false,latency: 150, // msdownload_throughput: (1600 * 1024) / 8, // bytes per secondupload_throughput: (750 * 1024) / 8,});
await driver.get('https://app.example.com/products');// ... measure
await driver.deleteNetworkConditions();var chrome = (ChromeDriver)driver;chrome.NetworkConditions = new ChromiumNetworkConditions{ IsOffline = false, Latency = TimeSpan.FromMilliseconds(150), DownloadThroughput = 1600 * 1024 / 8, // bytes per second UploadThroughput = 750 * 1024 / 8,};
driver.Navigate().GoToUrl("https://app.example.com/products");// ... measure
chrome.ClearNetworkConditions();Throughput values are passed through ChromeDriver to the DevTools network emulation, which works in bytes per second; double-check the unit in your binding’s API docs if the numbers look off by a factor of 1,024, since older docs describe it inconsistently.
Two limitations to know. First, this throttling is applied inside the browser’s network stack per request, not at the TCP level, so it approximates real slow networks (good for relative comparisons and loading states, not for absolute predictions). Second, it is Chromium-only. BiDi has a standard emulation.setNetworkConditions command (offline mode is the first part implemented); see WebDriver BiDi for status. CPU throttling, which matters as much as network on low-end phones, is available through CDP Emulation.setCPUThrottlingRate, as shown in Flaky Tests.
Lighthouse Alongside Selenium
Lighthouse runs a standardised audit (performance, accessibility, best practices, SEO) with its own throttling model and produces a score and a detailed report. It is better than hand-rolled metrics for one thing: comparable, well-understood numbers. It is worse at another: it audits a cold page load, not a state reached after a multi-step user journey.
The common integration pattern is to let Selenium do what it is good at (log in, set up state) and then point Lighthouse at the same browser through the remote debugging port:
# 1. Start Chrome with a fixed debugging port from your Selenium test:# options.addArguments("--remote-debugging-port=9222")# 2. After Selenium has logged in, run Lighthouse against the same browser:npx lighthouse https://app.example.com/dashboard \ --port=9222 \ --disable-storage-reset \ --only-categories=performance \ --output=json --output-path=./reports/dashboard.lighthouse.json--disable-storage-reset stops Lighthouse clearing cookies and storage, so the authenticated session Selenium created is reused. Lighthouse opens its own tab, so do not drive the browser from Selenium while the audit runs.
Lighthouse is a Node tool; from Java, Python or C# you invoke it as a subprocess and parse the JSON (categories.performance.score, audits['largest-contentful-paint'].numericValue). For a dedicated performance pipeline on public pages, Lighthouse CI (@lhci/cli) with its own assertions file is usually simpler than wiring Lighthouse into Selenium at all.
Tip: Run Lighthouse on a handful of key pages, not every test. Each audit takes 15 to 60 seconds. Use the in-test Performance API checks above for broad coverage and Lighthouse for depth.
Budgets as Assertions
Measuring is only useful if someone acts on regressions. Budgets turn measurements into pass/fail.
Pick the right metric type for the environment.
| Budget | Stability in CI | Good starting budget |
|---|---|---|
| JavaScript transfer size | Very high | Current size + 10% |
| Total page weight | Very high | Current size + 10% |
| Request count | High | Current count + small margin |
| FCP / LCP (lab, throttled) | Medium | Google’s “good” thresholds: FCP under 1.8 s, LCP under 2.5 s |
| CLS | High (deterministic layouts) | Under 0.1 |
| TTFB | Low on shared CI | Only on dedicated performance environments |
Control the noise for time-based budgets.
- Run on a dedicated, consistently sized agent, not alongside a parallel functional suite.
- Throttle network (and ideally CPU) so the browser, not the machine, is the bottleneck.
- Take the median of 3 to 5 loads in fresh sessions; a single sample is noise.
- Warm up the server first (one throwaway load) so you measure the front end, not a JIT compiling.
Store budgets in configuration, not in test code, keyed by page: { "/dashboard": { "lcp": 2500, "scriptKb": 350 } }. Changing a budget is then a reviewable, one-line change, and a page object can look up its own budget.
Trend, then gate. Record metrics per build (as a CI artifact, or pushed to a time-series store) for a few weeks before gating on them. You will learn your real variance and avoid setting a budget that fails one build in five.
static double medianLcp(Supplier<WebDriver> driverFactory, String url, int runs) { List<Double> samples = new ArrayList<>(); for (int i = 0; i < runs; i++) { WebDriver d = driverFactory.get(); // fresh profile each time: no cache try { d.get(url); Map<?, ?> v = (Map<?, ?>) ((JavascriptExecutor) d).executeAsyncScript(WEB_VITALS); samples.add(((Number) v.get("lcp")).doubleValue()); } finally { d.quit(); } } Collections.sort(samples); return samples.get(samples.size() / 2);}
double lcp = medianLcp(DriverFactory::newThrottledChrome, "https://staging.example.com/products", 5);assertTrue(lcp <= budgets.get("/products").lcp(), "Median LCP " + lcp + "ms over budget");import statistics
def median_lcp(driver_factory, url, runs=5): samples = [] for _ in range(runs): d = driver_factory() # fresh profile each time: no cache try: d.get(url) samples.append(d.execute_async_script(WEB_VITALS)["lcp"]) finally: d.quit() return statistics.median(samples)
lcp = median_lcp(new_throttled_chrome, "https://staging.example.com/products")assert lcp <= BUDGETS["/products"]["lcp"], f"Median LCP {lcp:.0f}ms over budget"async function medianLcp(driverFactory, url, runs = 5) {const samples = [];for (let i = 0; i < runs; i++) { const d = await driverFactory(); // fresh profile each time: no cache try { await d.get(url); samples.push((await d.executeAsyncScript(WEB_VITALS)).lcp); } finally { await d.quit(); }}samples.sort((a, b) => a - b);return samples[Math.floor(samples.length / 2)];}
const lcp = await medianLcp(newThrottledChrome, 'https://staging.example.com/products');assert.ok(lcp <= budgets['/products'].lcp, `Median LCP ${lcp}ms over budget`);static double MedianLcp(Func<IWebDriver> driverFactory, string url, int runs = 5){ var samples = new List<double>(); for (int i = 0; i < runs; i++) { using var d = driverFactory(); // fresh profile each time: no cache d.Navigate().GoToUrl(url); var v = (Dictionary<string, object>)((IJavaScriptExecutor)d).ExecuteAsyncScript(WebVitals); samples.Add(Convert.ToDouble(v["lcp"])); } samples.Sort(); return samples[samples.Count / 2];}
var lcp = MedianLcp(DriverFactory.NewThrottledChrome, "https://staging.example.com/products");Assert.That(lcp, Is.LessThanOrEqualTo(Budgets["/products"].Lcp), $"Median LCP {lcp}ms over budget");Keep these checks in a separate job from the functional suite. Performance assertions that run in the same parallel pool as 40 other browsers will measure contention, and the first time they fail for no reason, people will start ignoring them. For making the functional suite itself faster, which is a different topic, see Speeding Up Test Suites.
Summary
- Selenium measures single-user front-end performance; use k6, Gatling or JMeter for load.
- Navigation, Paint and Resource Timing via
executeScriptwork in every browser; LCP and CLS need a bufferedPerformanceObserverand are Chromium-first. - Throttle with the Chromium network-conditions API (or CDP) to make lab numbers meaningful and to exercise loading states.
- Use Lighthouse for depth on key pages, reusing a Selenium-authenticated browser via the debugging port.
- Gate on byte budgets first, time budgets later, using medians on a quiet, consistent environment.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.