1. Why Web performance tuning

The development of the Internet is very fast, website content is more and more, more and more powerful, more and more beautiful pages. More content means a slower website. But our users want the website to be faster and faster, so our front-end engineers only continue to carry out a continuous optimization of our website, in order to ensure that in the process of development, the speed of our website can always keep up with the needs of users’ experience.Amazon, for example, has a 100-millisecond delay on its network, which means it might sell 1% less goods. Google search is also very fast, and a 0.5 second delay on a search page can lead to a 20% drop in web traffic. Similarly, if an electronic trading platform is five milliseconds slower, a broker could lose $4 million per millisecond, which is pretty impressive.

2. Performance indicators and optimization objectives

Performance indicator 1: Network

The meaning of each time period in the picture:

  • Queueing: Browsers queue requests in the following cases:
    • Request with higher priority
    • Six TCP connections have been opened for this source, which is the limit. Only applicable to HTTP / 1.0 and HTTP / 1.1
    • The browser is temporarily allocating space in the disk cache
  • 例 句 : Any of the reasons described by Queueing cause the request to be delayed
  • DNS Lookup: Indicates the time spent by the browser to perform DNS Lookup on the requested IP address
  • Initial Conncection: The TCP connection must be established before the browser can send the request. This is the time it takes to initiate the connection
  • SSL: If your page is loaded using secure protocols such as SSL/TLS, this is the time the browser takes to establish a secure connection
  • Request sent: Indicates the time consumed by sending a Request
  • Waiting (TTFB) : The browser is Waiting for the first byte of the response. TTFB stands for Time To First Byte. The time is the combination of the time when the browser sends the request to the server, the time when the server processes the request, and the time when the first byte of the response packet reaches the browser.
  • Content Download: Time spent downloading resources

Some other fields:

  • Proxy negotiation: The time consumed by the browser negotiating with the Proxy server
  • ServiceWorker Preparation. The browser is starting the service worker.
  • Request to ServiceWorker. A Request is being sent to the service worker.
  • Receiving Push. The browser is Receiving response data pushed by the HTTP/2 server. .
  • Reading Push. The browser is Reading previously received local data.

About the meaning of grayAbout Size, whereBlack indicates the size of the resource requested from the network, and gray indicates the actual size of the resource.

Size is the sum of the Size of the request header and the request body. Due to the variety of HTTP requests, the Size of the data in the first row and the data in the second row may be different. The data in the first row may also be smaller than the data in the second row for the following reasons:

  • Has response headers, even including cookies (line 1 > line 2)
  • The request is cached (in general, line 1 < line 2)
  • Server GIZP compression (in general, first line < second line)

Reference article:

  1. Chrome DevTools — Network
  2. Learn to understand Chrome Network Waterfall in one minute

Performance indicator 2: The page auditing tool Chrome Lighthouse

Lighthouse is an open source automation tool for improving the quality of web pages. You can run it on any web page. It audits performance, accessibility, progressive Web applications, and more.

Specific use can refer to the article:

  1. Introduction to the page auditing tool Chrome Lighthouse
  2. Lighthouse tools

Performance indicator 3: Use the Show Frames per second meter

Mac uses command + Shift + P to open the command line tool to search for the Show Frames per second meter.

3.RAIL measurement model

Four aspects: Response, Animation, Idle, Load.

Response: Event processing should be completed within 50ms

  • The time for the user’s input to the response is less than 100ms, giving the user the feeling that it is completed in an instant.

Animation: Generates a frame in 10ms

  • Each frame should take no more than 10ms to generate. To ensure that the browser has 60 frames, each frame should take around 16ms, but the browser needs 6ms to render each frame.
  • Designed for visual smoothness. Users are sensitive to frame rate changes.

Idle: Maximizes the Idle time

  • Maximize idle time to increase the probability of responding to user input within 50ms

Load: Transfers content to the page within 5 seconds

  • Optimized for fast loading performance relative to the user’s device and network capabilities. Currently, the goal for the first load is to interact in five seconds or less on mid-range mobile devices with slow 3G connections.
  • For the second opening, try not to exceed 2 seconds

Tools used to analyze RAIL

  • Chrome DevTools
  • Lighthouse
  • WebPageTest

Reference article:

  1. Measure performance with the RAIL model
  2. Front-end performance optimization – Performance analysis with RAIL model

4. Commonly used performance measurement APIs

Navigation Timing, Resource Timing

In terms of front-end Performance metrics, the W3C defines a powerful Performance API. GetEntriesByType is a way to obtain performance data. Performance also provides getEntries and getEntriesByName. Due to time constraints, the difference is not explained here. Performance Timeline Level 2 or Performance MDN

Using performance. GetEntriesByType for containing the page load time value at each stage PerformanceEntry object, you can in the console output navTimes try.

const navTimes = performance.getEntriesByType('navigation')[0]
Copy the code

Step 1 start the timer

  • StartTime: records the startTime.

Step 2 Redirect

  • RedirectStart: indicates the redirection start time.
  • RedirectEnd: indicates the end time of redirection.

Step 3 Connect the browser to the server

  • FetchStart: time when the browser initiates an HTTP request.
  • DomainLookupStart: indicates the start time of DNS query.
  • DomainLookupEnd: indicates the end time of DNS query.
  • ConnectStart: indicates the start time of a TCP connection.
  • ConnectEnd: indicates the end time of TCP connection.

Step 4: The browser interacts with the server data

  • SecureConnectionStart: Indicates the time when the browser establishes a secure connection with the server.
  • RequestStart: The time when the browser starts sending data to the server.
  • ResponseStart: The time when the server starts sending data to the browser.
  • ResponseEnd: The time when the server ends sending data to the browser.

Step 5: Browser DOM parsing

  • DomLoading: the time when DOM parsing begins.
  • DomInteractive: the time when DOM parsing is complete and the embedded resources start to be loaded.
  • DomContentLoadedEventStart: need to be executed script has been parsed.
  • DomContentLoadedEventEnd: The time when the script that needs to be executed immediately has been executed.
  • DomComplete: The time when the document is parsed.

Therefore, calculate the first interaction time:

window.addEventListener('load', (event) => {
    // Time to Interactive
    let timing = performance.getEntriesByType('navigation')[0];
    let diff = timing.domInteractive - timing.fetchStart;
    console.log("TTI: " + diff);
})
Copy the code

After data is obtained, it needs to be reported to the server to achieve simple front-end performance monitoring.

Common time calculation

  • DNS resolution time: domainLookupEnd – domainLookupStart
  • TCP connection time: connectEnd – connectStart
  • SSL connection duration: connectEnd – secureConnectionStart
  • TTFB: responseStart – requestStart
  • Data transfer time: responseEnd – responseStart
  • DOM parsing time: domInteractive – responseEnd
  • Resource loading time: loadEventStart – domContentLoadedEventEnd
  • First Byte Time: responseStart – domainLookupStart
  • ResponseEnd – fetchStart
  • First interactive time: domInteractive – fetchStart
  • DOM Ready time: domContentLoadEventEnd – fetchStart
  • Page full load time: loadEventStart – fetchStart
  • HTTP header size: transferSize -encodedBodySize
  • Redirection number: performance. Navigation. RedirectCount
  • Redirection time: redirectEnd – redirectStart

Reference article:

  1. Detailed description of web performance parameter Performance API
  2. This section describes the front-end performance monitoring solution
  3. Performance MDN
  4. Performance Timeline Level 2

② Network APIs

var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.effectiveType;

function updateConnectionStatus() {
  console.log("Connection type changed from " + type + " to " + connection.effectiveType);
  type = connection.effectiveType;
}

connection.addEventListener('change', updateConnectionStatus);
Copy the code

③ Client and Server negotiation (HTTP Client Hints)

In the study...Copy the code

④ Webpage display status (UI APIs)

// Let vEvent = 'visibilitychange'; if (document.webkitHidden ! = undefined) { // webkit prefix detected vEvent = 'webkitvisibilitychange'; } function visibilityChanged() { if (document.hidden || document.webkitHidden) { console.log("Web page is hidden.") } else { console.log("Web page is visible.") } } document.addEventListener(vEvent, visibilityChanged, false);Copy the code