21

As a whole, it can be divided into the following steps:

  1. DNS domain name resolution;
  2. Establish a TCP connection (three-way handshake);
  3. Send HTTP request;
  4. The server processes the request;
  5. Return the response result;
  6. Close the TCP connection (four-way handshake);
  7. The browser parses HTML;
  8. Browser layout rendering;

1. DNS domain name resolution

The structure of the domain name

The domain name is . , [full domain name] from right to left are: root domain name, top-level domain name, second-level domain name, third-level domain name...

网址:https://www.baidu.com/
完整域名:www.baidu.com.root
省略域名:www.baidu.com.

root root domain, the global root domain name is root , so the root domain name is often ignored.
com top-level domain name, TLD (Top-Level Domains).
baidu secondary domain name, aliases include: secondary domain name, user DNS name server, authoritative name server
www third-level domain name

Why do I need DNS to resolve domain names to IP addresses?

Network communication requires corresponding network protocols, most of which are based on TCP/IP protocol, and TCP/IP protocol is based on IP address, so computer network communication can only recognize IP address. Because it is difficult for users to remember the IP address of each website, a "DNS server" appears.

What is DNS?

The DNS domain name system is to convert a domain name (for example: www.baidu.com) into an IP address. There is a one-to-one correspondence between domain names and IP addresses.

DNS resolution method

  • Forward resolution: The process of converting a domain name into a corresponding IP address. It is used when entering a website domain name in the browser address bar.
  • Reverse resolution: Find the corresponding registered domain name based on the IP address, which is often used by some background programs, and users cannot see it.

DNS query method

  • The query method between the client, the browser and the local DNS is recursive query .
  • The query method between the local DNS server and the root domain and its subdomains is iterative query .

Domain Name Resolution Record

can view the domain name resolution record

DNS resolution process

The parsing process is as follows:

first step: Check the browser cache
After the user browses a website through the browser, the browser will automatically cache the IP address corresponding to the domain name of the website. When the user visits again, the browser will look up the IP address corresponding to the domain name from the cache. If there is, complete the domain name resolution. If not, proceed to the next step.

  • Because the cache not only has a size limit, but also a time limit, there are cases where the corresponding domain name cannot be found.
  • Through chrome://net-internals/#dns you can view chrome's DNS cache information.

Step 2: Find the local hosts file
If it is not in the cache in the user's browser, the system will look for the mapping between this domain name and IP in its local hosts file. If so, complete the domain name resolution. If not, proceed to the next step.

  • Open the Finder application, press the three combination keys Shift+Command+G, enter the path where the Hosts file is located: /etc/hosts, you can view the local hosts.
The first two steps are all done on the local machine. Starting from the third step, a request to resolve the domain name is initiated to the remote DNS server.

Step 3: Initiate a domain name resolution request
If the domain name resolution is not completed on this machine, the system will request the local domain name resolution server for resolution, if yes, complete the domain name resolution, if not, proceed to the next step.

  • local domain name resolution server generally a domain name server in the region, such as a connected campus network, then the domain name resolution system is in the campus computer room, if it is connected to a telecommunications, mobile or China Unicom network, then the local domain name resolution server is located In this area, the respective operators provide services.
The first three steps are recursive queries, and the latter steps are iterative queries.

Step 4: Initiate a domain name resolution request
Obtain the host name corresponding to the root domain name server from the local domain name resolution server, and then initiate a resolution request root domain name server The root domain name server receives the request and returns the top-level domain name (gtld domain name) server address of the domain in question.

to the top-level domain name server
The local domain name resolution server top-level domain name server , and the top-level domain name server receives the request and returns the address of the second-level domain name server.

Step 6: Initiate a resolution request to the secondary domain name server
The local domain name resolution server second-level domain name server , and the second-level domain name server receives the request and returns the IP address to the local domain name server.

Step 7: Local domain name server caching results
The local domain name server caches the resolved results, and the cache time is controlled by time.

Step 8: Return the analysis result to the user
The resolution result will be directly returned to the user, and the user system will cache the address, and the cache time will be controlled. At this point, the resolution process ends.

Resolve the domain name command, www.baidu.com as an example:

  • Check the domain name result directly: nslookup www.baidu.com
  • View the entire analysis process: dig www.baidu.com +trace
    ​ Under normal circumstances, DNS resolution stops when the alias is reached, and the specific IP address is returned. If you want to see the specific address, you can further analyze the alias.

can be viewed: 1611c7ecad0637 Analysis of DNS domain name resolution process

2. Establish a TCP connection

What is TCP?

TCP/IP

If a computer and a network device want to communicate with each other, both parties must be based on the same rules (for example, which party initiates the communication first, which language is used for communication, how to send and receive data, how to end the communication, etc., different hardware, operation How to communicate between systems), this kind of rule is called a protocol. And TCP/IP is the general term for various Internet-related protocol families.

The TCP/IP protocol family is divided into layers: application layer, transport layer, network layer, data link layer, and physical layer.

Transport layer
This layer provides end-to-end communication for applications on two hosts. The transport layer has two transport protocols: TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).

Transmission Control Protocol TCP (Transmission Control Protocol)

  • It is a connection-oriented, reliable, full-duplex, byte stream-based transport layer communication protocol.

User Datagram Protocol UDP (User Datagram Protocol)

  • UDP does not need to establish a connection before transmitting data, and the remote host does not need to give any confirmation after receiving the UDP message.
  • Although UDP does not provide reliable delivery, in some cases UDP is indeed the most effective way of working (usually used for instant communication), such as: QQ voice, QQ video, live broadcast, etc.

TCP segment header format

  • source port and destination port : each occupies 2 bytes, which are the source port and the destination port respectively. An address can be determined by IP address + port number.
  • Sequense Number (seq) : Each byte in the byte stream transmitted in a TCP connection is numbered sequentially. This field indicates the sequence number of the first byte of the data sent in this segment. The initial sequence number is called Init Sequense Number, ISN.

    For example, the sequence number of a message segment is 101, with a total of 100 bytes of data. This means that the sequence number of the first byte of the data in this segment is 101, and the sequence number of the last byte is 200. Obviously, the data sequence number of the next message segment should start from 201, that is, the value of the sequence number field of the next message segment should be 201.

  • confirmation number ack : expect to receive the sequence number of the first data byte of the next segment of the other party. If the confirmation number is N, it means that all data up to the sequence number N-1 have been received correctly.

To the right of the reserved bits are 6 control bits, which are used to describe the nature of the message segment.

  • Urgent bit URG : When URG = 1, it indicates that there is urgent data in this segment, which is high-priority data and should be sent as soon as possible without queuing in the buffer.
  • Acknowledge ACK : The confirmation number field is valid only when ACK = 1, and the confirmation number is invalid when ACK = 0. TCP stipulates that ACK must be set to 1 in all message segments transmitted after the connection is established.
  • Push PSH : When two application processes communicate interactively, sometimes the application process at one end hopes to receive the response from the other immediately after typing a command. In this case, TCP can use push operations. At this time, the sender TCP sets PSH to 1, and immediately creates a segment and sends it out. The receiving TCP receives the segment with PSH = 1, and delivers it to the receiving application process as soon as possible. Instead of waiting for the entire cache to fill up before delivering upwards.
  • reset RST : When RST = 1, it indicates that a serious error has occurred in the TCP connection (for example, due to a host crash or other reasons). The connection must be released and the transmission connection must be re-established.
  • Synchronous SYN : SYN = 1 means this is a connection request or connection acceptance message.

    When SYN = 1 and ACK = 0, it indicates that this is a connection request segment. If the other party agrees to establish a connection, it should set SYN = 1 and ACK = 1 in the response segment.

  • terminates FIN : When FIN = 1, it indicates that the data sent in this segment has been sent, and the transport connection is required to be released.

How to establish a TCP connection between the client and the server?

The establishment of a TCP connection adopts the client-server model: the one that initiates the connection establishment actively is called the client, and the one that passively waits for the connection establishment is called the server. Perform a three-way handshake and establish a TCP connection.

so-called Three-way Handshake refers to the establishment of a TCP connection, the client and server are required to send a total of 3 packets.

The main function of the "three-way handshake" is to confirm whether the receiving and sending capabilities of both parties are normal, and to specify your own initialization sequence number (Init Sequense Number, ISN ) to prepare for the subsequent reliable transmission.

The specific process of the three-way handshake is as follows:

SYN : Whether it is a connection request/receive message segment;
seq : the sequence number of the first byte sent;
ACK : Whether it is an acknowledgment segment;
ack : Confirmation number. The sequence number of the first byte of the next data that you want to receive;

first handshake (SYN=1, seq=x)
The client sends a SYN message (SYN = 1) to the server. The message specifies the client's initialization sequence number ISN(x), that is, seq = x, which represents the sequence number of the first byte of the data sent in this message segment.

  • After the SYN message is sent, the client enters the SYN_SENT state, waiting for the server to confirm.
  • The client cannot confirm any;
    The server confirmed: The sender is normal, and the receiver is normal;

Second handshake (SYN=1, ACK=1, seq=y, ack=x+1)
The server receives the SYN message from the client, confirms the SYN message, and sends a SYN + ACK message to the client. The message specifies the server's initialization sequence number ISN(y), that is, seq = y, and the client's x+1 (ISN + 1) will be used as the value of the confirmation number ack, indicating that the SYN message sent by the client has been received Text, hope that the sequence number of the first byte of the next data received is x + 1.

  • After the message segment is sent, the server enters the SYN_RECV state.
  • The client confirmed that the sending and receiving by itself are normal, and the sending and receiving by the other party are normal;
    The server confirmed: the sender is normal, and the receiver is normal;

third handshake (ACK=1, seq=x+1, ack=y+1)
The client receives the SYN + ACK message from the server and sends an ACK message to the server. Taking the server's y + 1 (ISN + 1) as the value of ack, it means that the SYN message sent by the server has been received, and the sequence number of the first byte of the next data I hope to receive is y + 1, And specify that the client's serial number seq = x + 1 at this time (initially seq = x, so the second segment needs to be +1)

  • After the message segment is sent, both the client and the server enter the ESTABLISHED (connection successful) state, and the TCP three-way handshake is completed at this time.
  • The client confirmed that the sending and receiving by itself are normal, and the sending and receiving by the other party are normal;
    The server confirmed that the sending and receiving by itself is normal, and the sending and receiving by the other party are normal;

During the three-way handshake, the status of both parties in communication are as follows:

CLOSED : No connection status. The initial client and server are both in the CLOSED state.
LISTEN : Listening status, listening for connection requests from remote TCP ports.
SYN-SENT : Synchronization has been sent, waiting for a matching connection request after sending the connection request.
SYN-RCVD : Received synchronously. After the server is passively turned on, the state when it receives the SYN from the client and sends an ACK.
ESTABLISHED : The connection has been established and data transmission is possible.

The life version of the three-way handshake:

Client: "Hello, are you at home?" - SYN
Server: "Yes, come on." - SYN + ACK
Client: "Good." - ACK

  • In the third handshake, data can be carried. The first and second handshake must not carry data . Simply put, when requesting connection/reception, that is, SYN = 1 , data cannot be carried.
  • Ideally, once a TCP connection is established, the TCP connection will be maintained until either of the two parties actively closes the connection.
  • When one end sends its SYN to establish a connection, it chooses an initial sequence number for the connection. The ISN changes over time, so each connection will have a different ISN. If the ISN is fixed, the attacker can easily guess the subsequent confirmation number, so the ISN is dynamically generated .

3. Send HTTP request

After the TCP connection is established, the browser can send a GET request to the server to obtain web page information based on the HTTP/HTTPS protocol.

What is HTTP

Full name: Hypertext Transfer Protocol ( HyperText Transfer Protocol )
HTTP is a communication protocol ( protocol HTML and pictures (0611c7ecae6ace). It is an application layer protocol. Its messages are divided into request messages and response messages.
When the client requests a web page, it first encapsulates the requested content in a request message through the HTTP/HTTPS protocol. After receiving the request message, the server parses the message according to the protocol specification, and then returns a response message to the client .

The structure of the request message

Request line: request method (Method) + space + uniform resource identifier (URI) + space + HTTP version + CR LF.
request header: field name + colon + value + CR LF.
Blank line: CR LF. It means that all the header information about the request has been sent.
Request body: Not all requests have a body, which is added by the user. For example, requests to obtain resources: GET, HEAD, DELETE and OPTIONS, usually they do not need a body. Some requests send data to the server in order to update the data: a common situation is a POST request (containing HTML form data).

Open Baidu, the request message is as follows:

Why is there no request body in the request message in the browser?

Because for the convenience of developers, the browser puts the request body in Request Payload / QueryString / FormData under Request Headers The difference between the three can be viewed: What is Request Payload

Request method

Request methoddescribe
GETThe GET request will display the resource specified in the request. Generally speaking, the GET method should only be used for data reading, and should not be used for non-idempotent operations that have side effects.
POSTA POST request will submit data to the specified resource and request the server for processing, such as form data submission, file upload, etc. POST method is a non-idempotent , because this request may create new resources or/and modify existing resources.
PUTUsed to modify the resource as a whole. Idempotent.
DELETERequest the server to delete the resource. Idempotent.
OPTIONS1. Get the HTTP request method supported by the server. 2. Check the performance of the server. For example, in the pre-check for cross-domain requests, an HTTP OPTIONS request header needs to be sent to another domain name resource to determine whether the actual request sent is safe.
HEADThe HEAD request is the same as the GET request response, but only the header is returned in the response, and there is no response body. This method can obtain the meta-information contained in the response small message header without having to transmit the entire response content.
TRACEMainly used for testing or diagnosis. When a client initiates a request, the request may pass through a firewall, proxy, gateway, or some other application. Each intermediate node may modify the original HTTP request. The TRACE request will initiate a loopback diagnosis on the destination server, and carry the original request message it received in the response body. The client can view the entire request response chain, whether and how the original message has been destroyed or modified.
CONNECTIt is reserved in the HTTP/1.1 protocol to be able to change the connection to a proxy server in a pipe mode. Usually used for communication between SSL encrypted server link and non-encrypted HTTP proxy server.
PARCHUsed to partially modify resources. Not idempotent.

4. The server processes the request

The server receives the request and parses the request header.
If the header has cache-related information such as if-none-match and if-modified-since, verify whether the cache is valid, if it is valid, the return status code is 304, if it is invalid, the resource is returned again, and the status code is 200.
If there is no cache, the resource is returned directly.

5. Return the response result

After the server has processed the request, it responds to the client in the format of a response message.

Structure of response message

Status line: HTTP version + space + status code + space + status code description + CR LF.
response header: field name + colon + value + CR LF.
blank line: CR LF, which means that all the header information about the request has been sent.
Response body: Not all responses have a body, which is added by the user. Responses with status codes (such as 201 or 204 ) usually do not have a body.

Response status code

The status code is sent by the server in response to the client's request to the server.
1611c7ecae6e9e 1xx (message) request, continue processing
2xx (success)-the request has been successfully received and processed
3xx (redirect)-further action is required to complete the request
4xx (Client Error)-The request contains incorrect syntax or cannot be satisfied
5xx (server error)-the server could not satisfy an apparently valid request

6. Close the TCP connection

In order to avoid resource occupation and loss of both the server and the client, when there is no request or response to the two parties, either party can initiate a shutdown request. To close the TCP connection, you need to wave your hands four times.
so-called four waves of means that when a TCP connection is closed, the client and server are required to send a total of 4 packets.

The specific process of four waves is as follows:

FIN : Whether it is a termination segment;
seq : the sequence number of the first byte sent;
ACK : Whether it is an acknowledgment segment;
ack : Confirmation number. The sequence number of the first byte of the next data that you want to receive;

At the beginning, both parties are in the ESTAB-LISHED state, assuming that the client initiates a shutdown request first:

first wave (FIN=1, seq=u)
The client sends a FIN message requesting to terminate the connection. The message will specify an initial sequence number seq = u (ISN), stop sending data again, and actively close the TCP connection.

  • After sending the FIN message, the client is in the FIN_WAIT1 state, waiting for the server's confirmation.

second wave (ACK=1, seq=v, ack=u+1)
After the server receives the FIN message, it will send an ACK message. The message will specify an initial sequence number seq = v (ISN), and take the client's u+1 (ISN+1) as the value of ack, indicating that the client's message has been received.

  • After the message is sent, the server is in the CLOSE_WAIT state.
  • At this time, TCP is in a half-closed state, and the connection from the client to the server is released. After receiving the confirmation from the server, the client enters the FIN_WAIT2 state and waits for the connection release message segment sent by the server.

waved for the third time (FIN=1, ACK=1, seq=w, ack=u+1)
If the server also wants to disconnect (there is no data to send to the client), just like the first wave of the client, send a FIN message, and specify a sequence number w, and set the client's u+1 (ISN+ 1) As the value of ack, it indicates that the client's message has been received.

  • After the message is sent, the server is in LAST_ACK , waiting for the client's confirmation.

waved for the fourth time (ACK=1, seq=u+1, ack=w+1)
After the client receives the FIN message, it will send an ACK message. And specify a serial number u+1, and take the w +1 of the server as the value of ack.

  • After the message is sent, the client is in the TIME_WAIT state and waits for 2MSL to become the CLOSED state.

During the four-way handshake, the status of both parties in communication are as follows:

FIN-WAIT-1 : Waiting for the remote TCP connection interruption request, or the confirmation of the previous connection interruption request;
CLOSE-WAIT : Waiting for the connection interruption request sent from the local user;
FIN-WAIT-2 : Waiting for connection interruption request from remote TCP;
LAST-ACK : Waiting for the confirmation of the original connection interrupt request sent to the remote TCP;
TIME-WAIT : Wait enough time to ensure that the remote TCP receives the confirmation of the connection interruption request;

Four waved life version:

Client: "Brother, I have no data to transmit, let's close the connection." - FIN + seq
Server: "Received, let me see if there is data on my side." - ACK + seq + ack
Server: "Brother, I don't have any data to send to you, we can close the connection."-FIN + ACK + seq + ack
Client: "Good." - ACK + seq + ack

Why do I need to wait for 2MSL to enter the CLOSED state?

2MSL: Round-trip time of a message

The purpose of this is ensure that the server receives the ACK message sent by the client. If the server does not receive the ACK message from the client within the specified time, the server will resend the FIN message to the client. After the client receives the FIN message again, it will know that the previous ACK message has been lost , It will send an ACK message to the server again. After the server receives the ACK message, it closes the connection and is in the CLOSED state.

Why do you wave your hands four times?

Due to TCP's half-close (half-close) feature, TCP provides the ability for one end of the connection to receive data from the other end after finishing its sending. Either party can send a connection release notice after the data transfer is over, and enter the semi-closed state after the other party confirms. When the other party has no more data to send, a connection release notification will be sent. After the other party confirms, completely closes the TCP connection.
's terms, two handshake can release the TCP connection from one end to the other. To release the connection completely, a total of four handshake .

7. The browser parses HTML

The server returns HTML - after the response headers and data, the browser's rendering engine starts to parse the HTML.

Rendering engine parsing main process

The rendering engine parses HTML, generates a DOM tree, parses CSS, generates a CSSOM tree, and then combines the DOM tree and the CSSOM tree to build a rendering tree.

img

Build the DOM tree

The task of the HTML parser is to parse HTML tags into a DOM tree, involving tokenization and the structure of the tree.

  • HTML tags include opening and closing tags, as well as attribute names and values.
  • The DOM tree describes the content of the document. The <html> element is the first tag and the root node of the document tree. The tree reflects the relationship and hierarchical structure between different tags. Tags nested in other tags are child nodes. The greater the number of DOM nodes, the longer it takes to build the DOM tree.
  • DOM tree construction is incremental.

Build the CSSOM tree

The CSS parser will parse the CSS file into a CSSOM tree. The browser converts the CSS rules into a style map that can be understood and used, traverses each rule set in the CSS, and creates a node tree with parent, child, and sibling relationships based on the CSS selector.

  • CSS is rendering blocking: the browser will block the page rendering until it has executed all the CSS.
  • DOM and CSSOM are two trees, which are independent data structures.

Processing scripts and style sheets

Blocking rendering

"Rendering blocking" only refers to whether the browser needs to pause the first rendering of the webpage until the resource is ready.

JavaScript script

You can insert JavaScript scripts into html through the <script> tag. JavaScript is a dynamic language that runs in the browser.

default execution time of the script

JavaScript scripts are executed wherever they are inserted in the document. When the HTML parser encounters a <script> tag, it will suspend the construction of the DOM and transfer control to the JavaScript engine; when the JavaScript engine is finished, the browser will resume the DOM construction from where it left off.

script and other resources dependency

JavaScript can not only read and modify DOM properties, but also CSSOM properties. This creates a strong dependency between JavaScript, DOM and CSSOM, which may cause a significant delay in the browser's processing and rendering of web pages on the screen.

  • The position of the script in the document is very important, it is recommended to put it at the bottom of the document.
  • The JavaScript execution process relies on CSSOM and will not continue execution until CSSOM is ready.

For example: run a script to change the display attribute of the span element from none to inline

  • If the browser has not completed the construction of the DOM tree and the script is run at this time, there is no span tag, the script fails to run.
  • If the browser has not finished downloading and constructing the CSSOM tree, and running the script at this time, there will be race conditions. At this time, the browser will delay script execution and DOM construction until it completes the download and construction of CSSOM. This is not good for performance.

change the default behavior of the script

  • defer: download immediately, delay execution

The process of loading and rendering subsequent document elements will be parallel to the loading of the script (asynchronous), but the execution of the script will be after all the elements are parsed. Scripts will always be executed in the order of declaration.

<script defer="defer" src="example.js"></script>
  • async: Asynchronous script

The process of loading and rendering subsequent document elements will be performed in parallel with the loading and execution of the script (asynchronous), but the script is executed immediately after it is loaded, which will block the parsing of HTML. The script is executed immediately after downloading, not necessarily in the order of declaration.

<script async="async" src="example.js"></script>
async and defer attributes only work for outreach scripts, and will be automatically ignored when src

Style sheet

CSS is a rendering-blocking resource, which means that the browser will not render any processed content until the CSSOM tree is built. So it needs to be downloaded to the client as soon as possible, in order to shorten the first rendering time.

optimized style sheet download

By using media queries, we can declare style sheets based on specific use cases (such as display or printing), or based on dynamic conditions (such as screen orientation changes, size adjustment events, etc.). Only when the conditions are met, the browser will download and execute this first. css style sheet. (Regardless of whether there is a media query, the browser will download CSS resources, but the resources that do not block rendering have a lower priority)

<link href="style.css" rel="stylesheet">
<link href="style.css" rel="stylesheet" media="all">
<link href="portrait.css" rel="stylesheet" media="orientation:portrait">
<link href="print.css" rel="stylesheet" media="print">
  • The first statement blocks rendering and applies to all situations.
  • The second statement also blocks rendering: "all" is the default type. The first statement and the second statement are equivalent.
  • The third statement has dynamic media queries, which will be calculated when the page loads. Depending on the orientation of the device when the web page loads, portrait.css may or may not block rendering.
  • The fourth is only applied when printing a webpage, so when the webpage is first loaded in the browser, it will not block rendering.

In theory, applying a style sheet does not change the DOM tree, so there is no need to wait for the style sheet and stop document parsing. But if the script requests style information during the document parsing stage, the style has not been loaded and parsed. For this situation, different browsers have different solutions: Firefox will ban all scripts during the style sheet loading and parsing process. WebKit only prohibits the script if the style attributes that the script is trying to access may be affected by a style sheet that has not yet been loaded.

Build the render tree

The render tree includes content and styles: DOM and CSSOM trees are combined into a render tree. To construct the render tree, the browser checks each node, starting from the root node of the DOM tree, and adds its CSSOM rules to each visible node.

  • The render tree contains only visible content. The header (usually) does not contain any visible information, so it will not be included in the render tree. display: none; on an element, neither itself nor its descendants will appear in the render tree.
  • The rendering tree corresponds to the DOM tree, but not one-to-one. Non-visual DOM elements will not be inserted into the render tree.

8. The browser renders the page

layout

After the rendering tree is constructed, it enters the layout stage. The layout assigns each node an exact coordinate that should appear on the screen, which determines the width and height of each element, and the correlation between nodes.

  • The layout performance is affected by the DOM. The more nodes, the longer the layout time.

draw

After the layout is completed, enter the drawing stage, draw each node on the screen, which includes any visible parts such as text, color, picture, border, and shadow.

  • Drawing can decompose the layout elements into multiple layers. Promoting content to a layer on the GPU (rather than the main thread on the CPU) can improve first-time drawing and redrawing performance.

    Some specific attributes and elements can instantiate a layer, including <video> and <canvas> will-change CSS attribute is opacity, 3D transformation, 0611c7ecae78cd, etc. These nodes will be drawn on their own layer along with the child nodes.

  • Layers can indeed improve performance, but it comes at the cost of memory management, so it should not be overused as part of a web performance optimization strategy.
  • If the drawing on the screen is broken down into several layers, it needs to be combined.

synthesis

When the various parts of the document are drawn on different layers and overlap each other, they must be combined to ensure that they are drawn on the screen in the correct order and the content is displayed correctly.

Pixel pipeline

The browser runs a single frame rendering pipeline, called the pixel pipeline. If one or more of the links take too long to execute, users will feel stuck. The pixel pipeline is the key step of drawing pixels to the screen. There are five processes as follows:

JS/CSS —> Style —> Layout —> Paint —> Composite

JS/CSS : JS/CSS code changes.
Style : recalculate the style
Layout : recalculate the layout
Paint : draw
Composite : synthetic

At present, the refresh rate of most devices is 60 FPS. If the browser maintains each frame at about 60 FPS during the interaction, the user will not feel stuck. From a mathematical point of view, the budget per frame is approximately 16.7 milliseconds (1000 milliseconds / 60 frames = 16.66 milliseconds / frame). If JS is executed frequently or the execution time of JS is too long, it will cause the drawing time of each frame to be exceeded, then it will cause stalls, such as monitoring page sliding, animation, etc.

Worst performing pixel pipeline version: reflow

Change the geometric properties of the element (such as width, height, etc.), then the browser will check all the elements and "automatically rearrange" the page after the layout calculation. Any affected parts need to be redrawn, and the final drawn elements need to be synthesized.

The rearrangement is carried out at each step of the pixel pipeline, and the performance is greatly affected.

Average pixel pipeline version: replaint

Changing the background image, text color, or shadow of the element (the geometric size and position of the element remains unchanged) will not affect the page layout, and the Layout layout will be skipped, and the drawing and synthesis will be performed directly.

The best performing pixel pipeline version: avoid Layout and Paint

Using CSS properties that only trigger composite, you can avoid Layout and Paint.

Commonly used CSS properties that only trigger composite are: transform, opacity, pointer-events (whether to respond to mouse events), perspective (perspective effect), perspective-origin (perspective vanishing point), cursor (pointer style), orphans (settings) The minimum number of lines that must be kept at the bottom of the page when paging occurs inside the element (for printing or print preview), widows (set the minimum number of lines that must be kept at the top of the page when paging occurs inside the element (for printing or print preview) )).

csstriggers.com see if the change of each CSS property will trigger Layout/Paint/Composite.

时倾
794 声望2.4k 粉丝

把梦想放在心中