Moonlit Torii

My Front-End Performance Optimization Knowledge System

An original-source translation that organizes user-centered performance metrics and front-end optimization along the page-rendering process, from DNS and TCP to caching, HTTP/2, and rendering.

Original: rayne, “My Front-End Performance Optimization Knowledge System”

My Front-End Performance Optimization Knowledge System 2022-02-12 54,089 22-minute read

Preface

I have recently been studying front-end performance optimization. After reading many articles by experts, I felt that having so many scattered articles made learning less efficient. So I consolidated what those experts had written about performance optimization and built my own front-end performance optimization system around the page-rendering process. I originally intended to keep it for my own review; after all, this is a compilation rather than something I wrote myself. But with the spring hiring season just around the corner, I decided to share it with friends preparing for interviews, in the hope that it saves you some time. Most of the article is compiled from other sources. If any of the original authors object, please contact me and I will remove it.

To optimize a website's performance, we first need to learn how to measure it.

The RAIL model

image.png

User-centered performance metrics

  • First Paint (FP)
  • First Contentful Paint (FCP)
  • Largest Contentful Paint (LCP)
  • First Input Delay (FID)
  • Time to Interactive (TTI)
  • Total Blocking Time (TBT)
  • Cumulative Layout Shift (CLS)

FP & FCP

First Paint, or FP, records the time when the page first paints any pixel.

First Contentful Paint, or FCP, records the time when the page first paints text, an image, a non-empty Canvas, or SVG content.

These two metrics look very similar, but FP always occurs at or before FCP. The following figure shows the metrics for Juejin:

FP refers to painting pixels. For example, if a page has a gray background, FP is recorded as soon as that gray background appears. At that moment, however, DOM content may not have begun painting because files may still need to be downloaded and parsed. FCP is triggered only when DOM content changes—for example, when a piece of text is rendered. We can therefore regard both metrics as related to blank-screen time, so the faster they are, the better.

The figure above shows the officially recommended ranges. In other words, if both FP and FCP are completed within 2 seconds, the page offers an excellent experience.

LCP

Largest Contentful Paint, or LCP, records the time when the largest element in the viewport is painted. This time can change as the page renders because the largest element may change during rendering. The metric also stops being recorded after the user's first interaction. Its changes are shown below:

LCP actually reflects a page's performance better than the previous two metrics because it keeps updating. For example, when a skeleton screen or Loading animation appears, FCP has already been recorded, but the content the user actually wants to see has not yet appeared. What we really want to know is when the page's main content is presented.

The LCP metric helps us obtain exactly that information.

The figure above shows the officially recommended range: an experience is considered excellent when LCP is within 2.5 seconds.

TTI

Time to Interactive, or TTI, has a slightly complicated calculation. It must satisfy the following conditions:

  1. Start calculating after FCP.
  2. For 5 consecutive seconds, there must be no long task (a task taking more than 50 ms) and no more than two ongoing GET requests.
  3. Look back to the end time of the last long task before that 5-second window.

You may wonder why a long task is defined as one that exceeds 50 ms.

Google proposed the RAIL model:

For user interactions such as click events, the recommended response time is within 100 ms. To achieve this goal, tasks performed during idle time should take no more than 50 ms (the W3C also defines this standard), allowing the page to respond to interactions without the user noticing a delay.

Long tasks are also used in the FID and TBT metrics.

image.png

This is therefore a very important user-experience metric: it represents when the page truly becomes usable. Rendering content quickly is not enough; the page must also respond promptly to user interactions. You have probably encountered websites whose content is already visible but whose interactions remain sluggish, and which only become smooth after a while.

FID

First Input Delay, or FID, records the delay in responding to the user's first interaction with the page between FCP and TTI.

The metric is easy to understand: it measures how long it takes from the triggering of a user-interaction event until the page responds. If a long task occurs in between, the response time will inevitably increase.

As mentioned above, Google recommends responding to user interactions within 100 ms:

TBT

Total Blocking Time, or TBT, records the sum of the blocking time of all long tasks between FCP and TTI.

Suppose that, between FCP and TTI, the page runs the following long tasks (taking more than 50 ms) and short tasks (taking less than 50 ms):

The blocking time of each long task equals its total execution time minus 50 ms:

For the situation shown above, the total TBT is therefore 345 ms.

The value of this metric also affects TTI. In other words, the metrics related to long tasks are all interconnected.

CLS

Cumulative Layout Shift, or CLS, records unexpected layout movements on a page.

You have probably encountered situations like these: while a page is rendering, a huge image is suddenly inserted, or after clicking a button, a block of content is dynamically inserted. Such behavior has a major impact on the user experience. CLS was created for precisely this situation. It is calculated as: area affected by the shift * shift distance.

In the example above, the text moves by 25% of the screen height (shift distance), while 75% of the screen height is affected before and after the move (area affected by the shift). The CLS is therefore 0.25 * 0.75 = 0.1875.

The recommended CLS value is below 0.1. The lower it is, the less the page jumps around and the better the user experience. After all, few people enjoy having DOM content—such as an advertisement—suddenly inserted while they are reading or interacting with a page.

Now that all the metrics have been introduced, let us look at the three core user-experience metrics, how to obtain the corresponding metric data, and how to optimize them.

The three core metrics

In May 2020, Google proposed three core metrics for website user experience:

  • LCP
  • FID
  • CLS LCP represents page speed. Although other speed metrics exist, as explained above, LCP conveys more information. First, it updates in real time and provides more accurate data. Second, it represents the render time of the page's largest element. In general, quickly loading the largest element on a page makes users feel that the site performs well.

FID represents the page's interaction experience. No user wants the page to respond sluggishly after an interaction. Fast interaction responses make a page feel smooth.

CLS represents page stability and is especially important on mobile devices. Mobile screens are small, so a large CLS value makes the page feel particularly poor.

How to obtain the metrics

Lighthouse

You can install the Lighthouse extension to obtain the following metrics:

web-vitals-extension

This is an official tool. You can install the web-vitals-extension extension to obtain the three core metrics:

The web-vitals library

This is also an official tool. You can install the web-vitals package to obtain the following metrics:

The code is also very simple to use:

javascript
import {getCLS, getFID, getLCP} from 'web-vitals';

getCLS(console.log);
getFID(console.log);
getLCP(console.log);

Copy code

Chrome DevTools

Open Performance to quickly obtain the following metrics:

Before optimizing a website's performance, we first need to understand how a page is rendered so that we know which parts of the rendering process can be optimized.

The page-rendering process

image.png

  1. Enter the address
  2. Parse the URL
  3. Check the browser cache
  4. DNS resolution
  5. TCP/IP connection
  6. HTTP request
  7. The server processes the request and returns an HTTP message
  8. The browser renders the page
  9. Close the connection

Enter the address

When a user enters a query in the address bar, the address bar determines whether the input is search content or a requested URL.

  • If it is search content, the address bar uses the browser's default search engine to compose a new URL containing the search keywords.
  • If the input conforms to URL rules—for example, time.geekbang.org—the address bar adds a protocol according to those rules and composes a complete URL such as time.geekbang.org. When the user presses Enter, the current page is about to be replaced. Before the process continues, however, the browser gives the current page an opportunity to run the beforeunload event. This event allows the page to perform cleanup before exiting and to ask whether the user really wants to leave—for example, when a form has not yet been submitted. The user can therefore cancel navigation through beforeunload, preventing the browser from performing any subsequent work.

Parse the URL

A URL consists primarily of six parts: protocol, host, port, path, query parameters, and fragment. After a URL is entered, the browser parses the protocol, host, port, path, and other information, then constructs an HTTP request.

DNS resolution

Before initiating an HTTP request, the browser must first obtain the IP address of the page we want to visit. It sends a UDP packet to a DNS name-resolution server.

image.png

Optimization:

DNS pre-resolution

For large websites whose resources are distributed across multiple servers, DNS pre-resolution can resolve names in advance and reduce page stalls. WeChata927fb47ad19a95887884e244ccc127a.png

DNS load balancing

DNS also provides load balancing. Many websites now have multiple servers. If a high-traffic website sent every request to the same server, that server might crash. DNS load-balancing technology solves this problem. When a website has multiple server addresses, the DNS server returns a different resolution result—and therefore a different IP address—for each query, directing visits to different servers to balance the load. The result can be selected according to factors such as each machine's current load or its geographic distance from the user.

TCP/IP connection

The three-way handshake

TCP has six flag bits:

  • SYN (synchronous, establishes a connection)
  • ACK (acknowledgement)
  • PSH (push)
  • FIN (finish)
  • RST (reset)
  • URG (urgent) First handshake: Host A sends the server a packet with SYN=1 and a randomly generated Seq number=1234567. Host B knows from SYN=1 that A wants to establish a connection. (The browser initiates the first handshake and tells the server that it wants to send a request.)

Second handshake: After receiving the request, Host B confirms the connection information by sending A ack number=(Host A's seq+1), SUN=1, ACK=1234567 + 1, and a randomly generated Seq=7654321 packet. (The server initiates the second handshake and tells the browser that it is ready to receive, so the browser should send the request.)

Third handshake: After receiving the packet, Host A checks whether the ack number is correct—namely, the seq number sent the first time plus 1—and whether the SYN flag is 1. If both are correct, Host A sends ack number=(Host B's seq+1), ack=7654321 + 1. After Host B receives it and confirms that the Seq value matches ACK=7654321+ 1, the connection is successfully established. (The browser sends the third handshake, telling the server that it is about to send and that the server should be ready to receive.)

Check the browser cache

First, the network process checks whether the requested resource is cached locally. If a cached resource exists, it returns the resource directly to the browser process. If the resource cannot be found in the cache, it proceeds directly to the network-request process.

Optimization:

Enable browser caching

  1. Before sending a request, the browser checks the expires and cache-control request headers to determine whether the strong-cache policy is hit, including whether the cached entry has expired. If it is hit, the resource is obtained directly from the cache and no request is sent. Otherwise, continue to the next step.
  2. If the strong-cache rule is not hit, the browser sends a request and uses the If-Modified-Since and If-None-Match request headers to determine whether the negotiated cache is hit. If it is hit, the resource is obtained directly from the cache. Otherwise, continue to the next step.
  3. If neither of the first two steps is hit, obtain the resource directly from the server. Extract common third-party library modules

A WebApp normally consists of our own code and third-party libraries. Our code changes frequently, while third-party libraries do not change unless they receive a major version upgrade. Our code and third-party libraries should therefore be packaged separately. We can give third-party libraries a longer strong-cache lifetime so their code is not requested repeatedly.

How do we extract third-party libraries? In webpack 4.x, SplitChunksPlugin replaced CommonsChunkPlugin for extracting common modules. We can configure SplitChunksPlugin to split the bundles. For details, see Front-End Performance Optimization Trilogy (Loading).

HTTP request

Once the connection has been established, the browser constructs the request line, request headers, and other information; attaches data such as Cookies related to the domain to the request headers; and sends the constructed request information to the server.

Optimization:

Enable HTTP/2

After obtaining the HTML, the browser must parse it from top to bottom. It cannot request the related resources until it encounters script tags. Because of the browser's concurrency limit, it can make at most six requests at the same time. Is there a way around these limitations?

HTTP/2 is a very good solution. Its mechanisms are fast enough in themselves:

  1. HTTP/2 communicates using binary framing, whereas HTTP/1.x uses text, making HTTP/2 more efficient.

  2. HTTP/2 supports multiplexing: communication with the same domain requires only one TCP request channel, and requests and responses can communicate bidirectionally over that channel at the same time. HTTP/1.x must establish TCP for each request; multiple requests require multiple connections, and concurrency is limited, which is very time-consuming. image.png

  3. HTTP/2 supports header compression, saving network traffic used by message headers. Every HTTP/1.x request carries a large amount of redundant header information, wasting bandwidth. For example, of the two requests in the figure below, the first sends all header fields, while the second sends only the differences. This reduces redundant data and lowers overhead.

image.png

  1. HTTP/2 supports server push. Normally, after parsing HTML, the browser requests CSS and JavaScript resources only when it encounters the relevant tags. HTTP/2 can push the related resources directly without waiting for a request, greatly reducing the time spent on multiple requests. You can click this website to test HTTP/2.

Under a good network connection and on a high-performance device, HTTP/2 does not show an obvious advantage over HTTP/1.1. But the worse the network and device are, the more dramatically HTTP/2 affects loading. HTTP/2 can be said to have been created for the mobile web; on high-performance PCs with fiber connections, by contrast, its advantage is less obvious.

The server processes the request and returns an HTTP message

After receiving the request information, the server generates response data—including the response line, response headers, and response body—according to the request, then sends it to the network process. Once the network process has received the response line and response headers, it begins parsing the response-header content.

The browser renders the page

DOM tree

Bytes → characters → tokens → nodes → object model.

html
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="style.css" rel="stylesheet">
    <title>Critical Path</title>
  </head>
  <body>
    <p>Hello <span>web performance</span> students!</p>
    <div><img src="awesome-photo.jpg"></div>
  </body>
</html>
  • Conversion: The browser reads the raw bytes of HTML from disk or the network and converts them into individual characters according to the file's specified encoding, such as UTF-8.

  • Tokenization: The browser converts strings into the various tokens defined by the W3C HTML5 standard, such as “”, “”, and other strings inside angle brackets. Each token has a special meaning and a set of rules.

  • Lexical analysis: The emitted tokens are converted into “objects” that define their properties and rules.

  • DOM construction: Finally, because HTML markup defines relationships between different tags—some tags are contained inside others—the created objects are linked in a tree data structure. This structure also captures the parent-child relationships defined in the original markup: the HTML object is the parent of the body object, the body is the parent of the paragraph object, and so on.

CSS Object Model (CSSOM)

css
body { font-size: 16px }
p { font-weight: bold }
span { color: red }
p span { display: none }
img { float: right }

Layout Tree

  • The DOM tree and CSSOM tree are merged to form the render tree.

  • The render tree contains only the nodes needed to render the web page.

  • Layout calculates the exact position and size of every object.

  • The last step is painting, which uses the final render tree to render pixels to the screen.

Rendering

Rendering process:

  1. Divide the DOM into multiple layers after obtaining it.
  2. Calculate style results for the nodes in each layer (Recalculate style).
  3. Generate the geometry and position of each node (Layout—reflow).
  4. Paint and fill each node into the layer bitmap (Paint—repaint).
  5. Upload the layers to the GPU as textures.
  6. Combine multiple layers on the page to generate the final screen image (Composite Layers).

Creating layers

html
<div class="position_">position</div>
<div class="box_3d">3D transform</div>
<div class="will-change">will-change</div>
<div class="transform"></div>
<iframe src="https://www.baidu.com"></iframe>


div {width: 100px;height: 100px;}
.position_ {background: pink;position: fixed;z-index: 20;}
.box_3d {background: red;transform:  translate3d(100px,30px,10px);}
.will-change {background: #f12312;will-change: transform;}
.transform {background: #302912;transform: skew(30deg, 20deg);}

View Layers in Chrome. If Layers is not open, open it as shown below:

Knowing that layers exist, we can manually enable a layer by adding transform: translateZ(0). This reduces the cost of reflow and repaint and greatly improves efficiency. Do not overuse this property, however, or it will greatly increase memory consumption.—Enable GPU acceleration.

Reflow and repaint

  • Repaint When an element's style changes without affecting its position in the document flow—for example, color, background-color, or visibility—the browser applies the new style to the element and paints it again. This process is called repainting.

  • Reflow When the dimensions, structure, or certain properties of some or all elements in the Render Tree change, the browser renders some or all of the document again. This process is called reflow.

  • Reflow always causes repainting, but repainting does not necessarily cause reflow. Causes of reflow:

  1. The page is rendered for the first time.
  2. The browser window size changes.
  3. An element's dimensions or position change.
  4. An element's content changes, such as the amount of text or the size of an image.
  5. An element's font size changes.
  6. A visible DOM element is added or removed.
  7. A CSS pseudo-class, such as :hover, is activated.
  8. Certain properties are queried or certain methods are called. Properties and methods that cause reflow:
  • clientWidth, clientHeight, clientTop, clientLeft
  • offsetWidth, offsetHeight, offsetTop, offsetLeft
  • scrollWidth, scrollHeight, scrollTop, scrollLeft
  • scrollIntoView(), scrollIntoViewIffNeeded()
  • getComputedStyle()
  • getBoundingClientRect()
  • scrollTo()

Optimization:

Use a CDN for static resources

A content delivery network (CDN) is a group of Web servers distributed across different geographic locations. We know that latency increases as the server gets farther from the user. A CDN solves this problem by deploying servers in multiple locations, bringing the server closer to the user and shortening request time.

Prevent script blocking

Place CSS at the top of the file and JavaScript files at the bottom.

  1. CSS execution blocks rendering and prevents JavaScript from executing.

  2. JavaScript loading and execution block HTML parsing and prevent CSSOM construction. Image optimization

  3. Compress images.

  4. Lazy-load images.

  5. Use responsive images.

  6. Use images in WebP format. Compress files

The following plugins can be used for compression in webpack:

  • JavaScript: UglifyPlugin
  • CSS: MiniCssExtractPlugin
  • HTML: HtmlWebpackPlugin Use gzip compression. You can enable it by adding the gzip identifier to the Accept-Encoding header of an HTTP request. The server must also support this feature.

Reduce repaint and reflow

CSS

  1. Avoid table layouts.
  2. Change classes as close to the end of the DOM tree as possible.
  3. Avoid setting multiple layers of inline styles.
  4. Apply animation effects to elements whose position property is absolute or fixed.
  5. Avoid CSS expressions, such as calc(). JavaScript
  6. Avoid frequent style operations. Prefer rewriting the style property once, or define the style list as a class and change the class property once.
  7. Avoid frequent DOM operations. Create a documentFragment, apply all DOM operations to it, and finally add it to the document.
  8. You can also set display: none on an element before the operations and show it again when they finish. DOM operations on elements whose display property is none do not cause reflow or repaint.
  9. Avoid frequently reading properties that cause reflow or repaint. If a property must be used repeatedly, cache it in a variable.
  10. Use absolute positioning for elements with complex animations so that they leave the document flow; otherwise, they cause frequent reflow of the parent element and subsequent elements. Code Splitting

Split by route or even at component level. The approaches are largely similar. Component-level splitting lets us render only the necessary components while the page loads and load the remaining components on demand.

Tree Shaking

Tree Shaking uses program-flow analysis to identify and remove unused code. Without Tree Shaking, a great deal of code that is defined but never used still reaches and executes on the user's client, which is unquestionably a performance killer. Tree Shaking relies on the static characteristics of ES6 modules and removes unused code through analysis.

Skeleton (skeleton screen)

After the blank screen ends, the page begins to render, but at this point it may contain only a few meaningless elements, such as dropdown buttons, out-of-order elements, or navigation. Although these are parts of the page, they are not meaningful. What counts as meaningful?

  • For search-engine users, it is a complete set of search results.
  • For Weibo users, it is the Weibo content in their timeline.
  • For Taobao users, it is the product-page display. Between FCP and FMP (First Meaningful Paint), the page has started painting, but the page as a whole is still meaningless and the user remains anxious while waiting. Out-of-order or flickering elements may also appear, seriously affecting the experience. At this point, we may need user-experience optimizations.

Skeleton is a good approach and has now begun to be widely used. Its purpose is to reserve space in advance for the elements that will be rendered, prevent flashing, tell the user that content is about to appear, and reduce the user's anxiety.

Use server-side rendering

Client-side rendering: Obtain the HTML file, download JavaScript files as needed, run the files, generate the DOM, and then render it.

Server-side rendering: The server returns an HTML file, and the client only needs to parse the HTML.

text
Advantages: Fast first-screen rendering and good SEO.
Disadvantages: Complicated configuration and increased computational pressure on the server.

(Pseudo) server-side rendering

Since there is waiting time between loading the HTML and executing JavaScript, why not render directly on the server? The returned HTML would already contain the complete DOM structure, saving the work of invoking JavaScript to create all kinds of DOM nodes. It would also be SEO-friendly.

This need is exactly why both Vue and React support server-side rendering, and why related frameworks such as Nuxt.js and Next.js are so popular. Of course, the cost is too high for applications that have already adopted client-side rendering.

Someone therefore devised a solution. Google open-sourced a library called Puppeteer, which is effectively a headless browser. Through it, we can use code to simulate all kinds of browser operations. For example, we can use Node to save HTML as a PDF, simulate clicks and form submissions on the back end, and naturally also simulate the browser to obtain the HTML structure of the first screen.

prerender-spa-plugin is a plugin based on the principle above. It simulates a browser environment locally and executes our bundle in advance, allowing the first screen's HTML to be obtained through parsing. In a normal environment, we can then return that pre-parsed HTML.

Close the connection

  1. At first, both sides are in the established state. Suppose the client initiates the close request.

  2. First wave: The client sends a FIN message containing a specified sequence number. The client is now in the FIN_WAIT1 state.

  3. Second wave: After receiving the FIN, the server sends an ACK message and uses the client's sequence-number value + 1 as the ACK message's sequence-number value, indicating that it has received the client's message. The server is now in the CLOSE_WAIT state.

  4. Third wave: If the server also wants to close the connection, it sends a FIN message with a specified sequence number, just as the client did in the first wave. The server is now in the LAST_ACK state.

  5. Some time must pass to ensure that the server receives its own ACK message before entering the CLOSED state. After receiving the ACK message, the server closes the connection and enters the CLOSED state. Reference links:

  6. Front-End Performance Optimization Trilogy (Loading)

  7. 24 Front-End Performance Optimization Suggestions (2020)

  8. Building a Front-End Knowledge System Starting from Entering a URL

  9. End-to-End Front-End Performance Optimization (Worth Saving)

  10. Still Reading Those Outdated Performance Optimization Articles? Learn About These Latest Performance Metrics

  11. How Browsers Work and Practice