This tutorial demonstrates how to leverage the Performance API to capture detailed performance metrics from real users interacting with your web application. While browser DevTools offer performance insights, they don't accurately reflect the diverse real-world conditions users experience across various devices, locations, and network connections.
Key Benefits of the Performance API:
Understanding the Performance API:
The Performance API employs a buffer to store performance metrics as objects at key stages of a webpage's lifecycle:
API support can be checked with:
if ('performance' in window) { // Use Performance APIs }
Note: Safari's support for all methods isn't complete, despite implementing the majority of the API. The custom timing APIs are also available in Node.js (using the perf_hooks
module) and Deno (requires --allow-hrtime
).
Beyond Date()
:
While Date()
can measure elapsed time, its millisecond precision and reliance on system time (susceptible to OS adjustments) limit its accuracy. The Performance API's high-resolution timer and additional metrics (like redirect and DNS times) provide superior detail.
Recording and Reporting Metrics:
Client-side performance data needs a destination. You can send this data to your server for analysis using AJAX, Fetch, XMLHttpRequest, or the Beacon API. Many analytics platforms also offer custom event APIs for recording timings (e.g., Google Analytics User Timings API).
Page Navigation Timing:
Testing on fast connections doesn't reflect real-user experiences. The Navigation Timing API provides a PerformanceNavigationTiming
object containing detailed information about redirects, load times, file sizes, DOM events, and more, as observed by the user.
Access this object using:
if ('performance' in window) { // Use Performance APIs }
or
const pagePerf = performance.getEntriesByType('navigation');
Both return an array with a single object containing read-only properties (e.g., startTime
, duration
, domComplete
, various timing metrics).
Page Resource Timing:
The Resource Timing API provides PerformanceResourceTiming
objects for each loaded asset (images, CSS, scripts, etc.). Use:
const pagePerf = performance.getEntriesByName(window.location);
This returns an array of objects, each with timing properties similar to navigation timing, but without navigation and DOM event data. Individual resources can be accessed using getEntriesByName()
.
Example: Analyzing CSS file load times and sizes:
const resPerf = performance.getEntriesByType('resource');
Browser Paint Timing:
The Paint Timing API provides PerformancePaintTiming
objects for first-paint
and first-contentful-paint
, crucial for assessing perceived performance. Access them with:
const css = performance.getEntriesByType('resource') .filter(r => r.initiatorType === 'link' && r.name.includes('.css')) .map(r => ({ name: r.name, load: r.duration + 'ms', size: r.decodedBodySize + 'bytes' }));
User Timing (Custom Metrics):
The Performance API allows custom timing of application functions using performance.now()
, .mark()
, and .measure()
. performance.now()
provides high-resolution timestamps. .mark()
creates named markers in the performance buffer, and .measure()
calculates the duration between markers. PerformanceObserver
allows asynchronous observation of performance entries.
Self-Profiling API:
The Self-profiling API (still under development) simplifies performance analysis by automatically sampling execution, identifying potential bottlenecks without manual marker placement.
Conclusion:
The Performance API empowers developers to accurately measure and improve web application performance based on real-user data, enabling targeted optimization and a superior user experience. Remember to consult the detailed documentation for the most up-to-date information and specific property details.
The above is the detailed content of How to Make Your Site Faster with the Performance API. For more information, please follow other related articles on the PHP Chinese website!