[JS] 1691- Re-learn JavaScript API – Performance API

e1f905627fb083afa72aea2e8a772056.jpeg

?

Previous review:

1. Page Visibility API

2. Broadcast Channel API

3. Beacon APIs

4. Resize Observer API

5. Clipboard API

6. Fetch API

?

1. What is Performance API

1.1 Concept introduction

The Performance API provides methods for Accessing and measuring information about browser performance. Through the Performance API, developers can obtain information about “Page Load Time”, “Resource Load Performance”, “User Interaction Latency”, etc. Detailed information for performance analysis and optimization.

1.2 Functions and usage scenarios

The role of Performance API is to help developers locate and solve performance problems, optimize webpage loading speed and user experience. It can be used in the following scenarios:

  • “Webpage Performance Monitoring”

Measure and analyze page loading time, resource loading performance, critical rendering path and other indicators to understand web page performance bottlenecks.

  • “Performance Optimization”

Identify potential performance issues and take appropriate optimization measures to improve web page loading speed and responsiveness.

  • User Experience Analysis

Evaluate the user quality of experience of web pages by measuring user interaction latency and animation performance.

  • “Performance Benchmarking”

Compare the performance differences under different versions or different configurations, and evaluate the effect of performance improvement.

2. How to use

The Performance API provides a set of methods and properties for obtaining and measuring performance-related information. Here are some common usage examples:

  • “Get Page Load Time”

const loadTime =
  window.performance.timing.loadEventEnd-
  window.performance.timing.navigationStart;

console.log(`Page load time: ${loadTime}ms`);
  • “Measuring resource load times”

const resourceTiming = window. performance. getEntriesByType("resource");
resourceTiming. forEach((resource) => {
  console.log(`Load time for ${resource.name}: ${resource.duration}ms`);
});
  • “Monitor user interaction latency”

const interactionStart = Date.now();
document. addEventListener("click", () => {
  const interactionEnd = Date. now();
  const interactionDelay = interactionEnd - interactionStart;
  console.log(`User click delay: ${interactionDelay}ms`);
});

Please note that these codes are just examples, and actual use may require “proper processing and compatibility detection according to specific needs and browser compatibility”.

3. Practical application

The Performance API can be applied to many scenarios and optimization scenarios, here are a few common examples:

3.1 Web page loading time monitoring and optimization

Through the Performance API, we can monitor the loading time of the page and optimize it. Here is a sample code to monitor page load time and resource load time:

// Monitor page load time
const loadTime =
  window.performance.timing.loadEventEnd-
  window.performance.timing.navigationStart;

console.log(`Page load time: ${loadTime}ms`);

// Monitor resource loading time
const resourceTiming = window. performance. getEntriesByType("resource");
resourceTiming. forEach((resource) => {
  console.log(`Load time for ${resource.name}: ${resource.duration}ms`);
});

By getting the timestamp in the window.performance.timing object, we can calculate the loading time of the page. In addition, through the window.performance.getEntriesByType('resource') method, we can get the loading performance information of all resources to further optimize resource loading.

3.2 Resource loading performance analysis

For key resources in web pages, we usually need to pay attention to their loading time for performance optimization. Through the Performance API, we can monitor and analyze the loading performance of key resources. Here is a sample code to monitor the loading time of a specified key resource:

// Monitor the loading time of key resources
const keyResources = [
  "https://example.com/css/style.css",
  "https://example.com/js/main.js",
];
keyResources. forEach((resource) => {
  const resourceEntry = window. performance. getEntriesByName(resource)[0];
  console.log(`Load time of ${resource}: ${resourceEntry.duration}ms`);
});

By using the window.performance.getEntriesByName() method, we can obtain the loading performance information of a specific resource, and then analyze and optimize the loading time of key resources.

3.3 User interaction delay monitoring

User experience is one of the crucial factors in web development. The Performance API helps us monitor the latency of user interaction with web pages for optimization. Here is a sample code to monitor user click delay:

// Monitor user click delay
const interactionStart = Date. now();
document. addEventListener("click", () => {
  const interactionEnd = Date. now();
  const interactionDelay = interactionEnd - interactionStart;
  console.log(`User click delay: ${interactionDelay}ms`);
});

By recording the start time and end time of user interaction, we can calculate the delay time of user clicks to help us evaluate and improve user experience.

3.4 Page animation performance monitoring

Using animations in web pages can enhance user experience, but poor implementation of animations can lead to performance issues. Through the Performance API, we can monitor the performance of page animations for optimization. Here is a sample code for monitoring animation execution time:

// Monitor animation performance
function measureAnimationPerformance() {
  const animationStart = performance. now();
  // perform animation
  requestAnimationFrame(() => {
    const animationEnd = performance. now();
    const animationDuration = animationEnd - animationStart;
    console.log(`Animation execution time: ${animationDuration}ms`);
  });
}

measureAnimationPerformance();

In this example, we use the performance.now() method to get the start time and end time of the animation, and calculate the execution time of the animation. By monitoring the animation performance, we can judge whether the animation is smooth and whether it takes up too many resources, so as to optimize and improve it.

4. Compatibility and pros and cons

4.1 Compatibility

The following is the compatibility of Performance API on different browsers:

  • Chrome 6+?

  • Firefox 7+?

  • Safari 8+?

  • Edge 12+?

  • Internet Explorer: Partially supported, supports IE 9+

It is recommended that in actual development, compatibility testing should be performed based on the browser usage of the target users, and alternative solutions should be provided or polyfills should be used to fill in compatibility differences as needed.

c105a081dfebc2e60eb691b4aaeb2a81.png

For detailed compatibility information, please visit Can I use[1].

4.2 Advantages and disadvantages

The Performance API has the following advantages and disadvantages:

advantage:

  • Provides “rich performance indicators and measurement methods”, which can comprehensively evaluate the performance of web pages.

  • Supports obtaining key indicators such as page loading time, resource loading performance, user interaction delay, etc., to help developers locate and solve performance problems.

  • Capable of performance optimization and user experience analysis, “improve the loading speed and responsiveness of web pages”.

shortcoming:

  • In some cases, obtaining performance indicators may have a certain impact on web page performance, so it needs to be used with caution.

  • May not be supported in some older browsers, “Requires compatibility or workaround”.

  • The accuracy of some indicators may be limited by browser implementation and device performance, and comprehensive consideration and verification are required.

When using, it needs to be used and handled reasonably in combination with actual needs and compatibility requirements.

4.3 Tool recommendation

Recommend several third-party libraries based on Performance API encapsulation:

  1. Web Vitals[2]: 6.1K?

A library for measuring and monitoring core web performance indicators, based on the Performance API, including Largest Contentful Paint (LCP), First Input Delay (FID), Cumulative Layout Shift (CLS) and other indicators.

  1. Perfume.js[3]: 2.8K?

A small but powerful performance measurement library that can be used to monitor page load time, critical resource load time and user interaction latency.

  1. PerformanceNow.js[4]: 100?

A small performance timing library, based on the high-resolution timestamp of the Performance API, providing more accurate performance measurement functions.

These libraries are encapsulated and extended on the basis of Performance API, providing more convenient interfaces and functions to help developers better monitor and optimize web page performance. We can choose a suitable library according to specific needs to simplify the work of performance monitoring and analysis.

5. Use suggestions and precautions

Summarize the usage suggestions and precautions of several Performance APIs:

  1. When measuring performance, you should choose the right timing and target to avoid extra burden on page performance.

  2. Pay attention to compatibility issues, perform compatibility testing and processing according to the target browser, consider using polyfills or alternatives.

  3. Combine with other tools and methods, such as browser developer tools, performance analysis tools, etc., to comprehensively analyze and optimize the performance of web pages.

  4. Know what the different metrics mean and interpret to avoid misinterpreting or misinterpreting performance data.

  5. Use performance data for targeted optimization, prioritizing bottlenecks affecting user experience.

  6. Follow the latest changes and enhancements to the Performance API as browsers are updated and standards evolve.

6. Summary

The Performance API is an important JavaScript API for accessing and measuring browser performance related information. It provides a wealth of performance indicators and measurement methods to help developers locate and solve performance problems, optimize web page loading speed and user experience. Through the Performance API, key indicators such as page loading time, resource loading performance, and user interaction delay can be obtained for performance analysis and optimization.

7. Extended learning

If you are interested in Performance API, you can refer to the following materials for further study:

  • MDN web docs – Performance API[5]

  • Google Developers – Assessing Loading Performance in Real Life with Navigation and Resource Timing[6]

Hope this article helps you understand and use the Performance API. If you have any questions, please feel free to ask.

Reference

[1]

Can I use: https://caniuse.com/?search=Performance API

[2]

Web vitals: https://github.com/GoogleChrome/web-vitals

[3]

Perfume.js: https://github.com/Zizzamia/perfume.js

[4]

PerformanceNow.js: https://github.com/myrne/performance-now

[5]

MDN web docs – Performance API: https://developer.mozilla.org/en-US/docs/Web/API/Performance

[6]

Google Developers – Assessing Loading Performance in Real Life with Navigation and Resource Timing: https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing

Past review

#

How to develop React functional components using TypeScript?

#

11 React Misuses to Avoid

#

6 essential VSCode plugins for Vue3 development

#

3 very useful Node.js version management tools

#

6 ref and reactive issues in Vue3 that you must understand

#

6 unexpected JavaScript problems

#

Try to understand the essence of low-code platform design from another angle

68c7ca52510e5e4e79fcc59e3098f889.gif

Reply to “Join group” to learn and progress together