Home > Web Front-end > JS Tutorial > How to Make Your Site Faster with the Performance API

How to Make Your Site Faster with the Performance API

Lisa Kudrow
Release: 2025-02-10 14:53:15
Original
608 people have browsed it

How to Make Your Site Faster with the Performance API

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:

  • Real-world Accuracy: The Performance API provides a far more realistic picture of application performance compared to isolated DevTools testing.
  • Comprehensive Metrics: It captures metrics throughout the page lifecycle, including navigation, resource loading, rendering, and custom application logic execution times.
  • High-Resolution Timing: Utilizing a high-resolution timer, it records timings down to fractions of a millisecond, capturing details like redirect and DNS lookup times, impossible with standard timers.
  • Customizable Measurement: Allows precise timing of your application's functions, working seamlessly across client-side JavaScript, Web Workers, Deno, and Node.js.
  • Cross-Platform Analysis: Enables performance measurement on actual user devices and networks, simplifying bottleneck identification and performance optimization.

Understanding the Performance API:

The Performance API employs a buffer to store performance metrics as objects at key stages of a webpage's lifecycle:

  1. Page Navigation: Records redirects, connections, handshakes, and DOM events.
  2. Resource Loading: Tracks the loading times of assets like images, CSS, scripts, and AJAX calls.
  3. Paint Metrics: Captures browser rendering information (e.g., First Contentful Paint).
  4. Custom Performance: Enables measurement of arbitrary application processing times to pinpoint slow functions.

API support can be checked with:

if ('performance' in window) {
  // Use Performance APIs
}
Copy after login
Copy after login

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
}
Copy after login
Copy after login

or

const pagePerf = performance.getEntriesByType('navigation');
Copy after login

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);
Copy after login

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');
Copy after login

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'
  }));
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template