define

The Performance interface can obtain Performance related information on the current page. It is part of the High Resolution Time API, It also integrates the Performance Timeline API, Navigation Timing API, User Timing API, and Resource Timing API.

Note: This interface and its members are available in the Web Worker, except as indicated below. Also, note that performance is created and measured in the same environment. That is, if you create a performance on the main thread (or another worker), it is not available on another worker thread; And vice versa.

Explanation of common nouns
  1. First Paint (FP) is drawn for the First time
  2. FCP (First Contentful Paint) First content painting
  3. LCP (Largest Contentful Paint)Max content rendering
  4. DCL (DomContentloaded)
  5. FMP(First Meaningful Paint) is First effectively drawn
  6. L (onLoad)
  7. TTI (Time to Interactive) Indicates the interaction Time
  8. Total Blocking Time (TBT) Total Blocking Time of the Blocking page
  9. FID (First Input Delay) First Input Delay
  10. CLS Cumulative Layout Shift (CLS) Cumulative Layout Shift
  11. SI (Speed Index)
Performance API
MDN Web docs describe
Resource Timing API Get and analyze detailed network timing data for application resource loads
Navigation_timing_API Provides data that can be used to measure the performance of a website
Performance Support client side delay measurement in applications
Performance_Timeline Provides data that can be used to measure the client latency of an application
User_Timing_API Allows developers to create application-specific timestamps in the browser performance timeline
Frame_Timing_API Provides frame timing data about the browser event loop
Network_Information_API You can obtain the network connection information of the system, and the application can present different high-definition content to the user based on this information
Navigation Timing: Processing Model
  1. Navigation Timing Level 1

  1. Navigation Timing Level 2

  • Last document uninstall
  • redirect
  • The browser is ready to grab the document using HTTP
  • Checking the local cache
  • Querying DNS Domain Names
  • TCP Establishing a connection
  • HTTP request and response
  • Render the DOM tree and parse it
  • The page starts loading resources
  • Ready triggers the load event to execute the callback function

Performance report

// The onload event is triggered. - Wait 1s. - Performance is reported
var page = windows.performance.timing
// DNS
dns = page.domainLookupEnd - page.domainLookupStart
// TCP
tcp = page.connectEnd - page.connectStart
// Request return time
connectTime = page.responseEnd - page.requestStart
// Server response time
responseTime = page.responseEnd - page.responseStart
// DOM analysis duration
domAnalysis = page.domComplete - page.domInteractive
// Dom render time
domReady = page.domContentLoadedEventEnd - page.navigationStart
// The total time the page takes to load
loadTime = page.loadEventEnd - page.navigationStart
Copy the code
PerformanceNavigation(To be abandoned)

attribute

  1. RedirectCount: The page is redirected several times, if any
  2. type
type describe
0 TYPE_NAVIGATENEXT normal page (not refreshed, not redirected, etc.)
1 That is, TYPE_RELOAD is refreshed via window.location.reload()
2 That is, TYPE_BACK_FORWARD page entered through the browser’s forward and back buttons (history)
255 That is, TYPE_UNDEFINED specifies the page that is not entered in the above method
methods
  1. Performance.getEntries()
  2. Performance.getEntriesByType()
  3. Performance.getEntriesByName()
  4. Performance. Now () accurately calculates the running time of the program
Mark, Measures calculates the program time
  1. Performance.mark () marks various time stamps for typing
  2. The performance measure () measurement
  3. Performance.clearmarks () clears the dots
  4. Performance. ClearMeasures () to clear the measurement data
function randomFunc (n) {  
    if(! n) {// Generate a random number
        n = ~~(Math.random() * 10000);
    }
    var nameStart = 'markStart' + n; 
    var nameEnd   = 'markEnd' + n; 
    // Make a mark before the function executes
    window.performance.mark(nameStart);
 
    for (var i = 0; i < n; i++) {
        // do nothing
    }
 
    // Make a mark after the function is executed
    window.performance.mark(nameEnd);
 
    // Then measure the time distance between the two markers and save it
    var name = 'measureRandomFunc' + n;
    window.performance.measure(name, nameStart, nameEnd);
}
 
// Execute it three times
randomFunc();  
randomFunc();  
// Specify a name
randomFunc(888);

// Take a look at the saved mark
window.performance.getEntriesByType('mark')

// Take a look at the saved measures
window.performance.getEntriesByType('measure');

// Clear the specified flag
window.performance.clearMarks('markStart888');  
// Clear all flags
window.performance.clearMarks();
 
// Clear the specified measurement
window.performance.clearMeasures('measureRandomFunc');  
// Clear all measurements
window.performance.clearMeasures(); 


Copy the code
White screen, first screen rendering duration
Performance indicators define measure
hang The first time a user can stabilize interaction with a page FCP
The first screen The time when the content of the visual area has been substantially rendered LCP
/* * Obtain the blank screen duration * */

function getFirstPaint() {
  let firstPaints = {};
  if (typeof performance.getEntriesByType === 'function') {let performanceEntries = performance.getEntriesByType('paint') | | []; performanceEntries.forEach((entry) = > {
      if (entry.name === 'first-paint') {
        firstPaints.firstPaint = entry.startTime;
      } else if (entry.name === 'first-contentful-paint') { firstPaints.firstContentfulPaint = entry.startTime; }}); }else {
    if (chrome && chrome.loadTimes) {
      let loadTimes = window.chrome.loadTimes();
      let {firstPaintTime, startLoadTime} = loadTimes;
      firstPaints.firstPaint = (firstPaintTime - startLoadTime) * 1000;
    } else if (performance.timing && typeof performance.timing.msFirstPaint === 'number') {
      let{msFirstPaint, navigationStart} = performance.timing; firstPaints.firstPaint = msFirstPaint - navigationStart; }}return firstPaints;
}


/* * Get the first screen duration */
try {
  const po = new PerformanceObserver((entryList) = > {
    const entries = entryList.getEntries();
    const lastEntry = entries[entries.length - 1]; // renderTime takes precedence, if not loadTime
    let lcp = lastEntry.renderTime || lastEntry.loadTime;
    window.perfData.push({ 'LCP', lcp });
  });
  po.observe({type: 'largest-contentful-paint'});
} catch (e) { // Do nothing }

Copy the code
FPS calculation (check if the page is stuck)
/ / FPS detection
(() = > {
    const limit = 3;                        // The maximum number of consecutive occurrences of low FPS
    const below = 20;                       // Minimum FPS that can be tolerated
    let count = 0;
    let lastTime = performance.now();
    let frame = 0;
    let lastFameTime = performance.now();
    let fps = 0;
    
    const loop = () = > {
        frame += 1;
        const now = performance.now();
        const fs = (now - lastFameTime);
        lastFameTime = now;
        
        // 1000 ms FPS (optional, depending on your choice)
        fps = Math.round(1000 / fs);
        
        if (now > 1000 + lastTime) {
            // FPS in 1s
            fps = Math.round((frame * 1000) / (now - lastTime));
            frame = 0;
            lastTime = now;
        }
        if (fps < below) {
            count += 1;
            if (count >= limit) {
                console.log('Web page stuck'.Continuous `${count}Time FPS below${below}, the current FPS is${fps}`);
                BUS.trigger('fps-low');    // Close some JS animations}}else {
            count = 0;
        }
        window.requestAnimationFrame(loop); }; loop(); }) ();Copy the code
Refer to the article
  1. Performance – Monitoring web page and application performance
  2. Gets the time required for each stage of page loading
  3. Navigation Timing Level 2