This article tells about from the input URL to complete the page load involved in part of the browser knowledge, network knowledge, front-end related knowledge, etc., the content of the reference to a number of big guy’s article, if there is a mistake, please kindly comment!
The overview diagram
Browser Basics
Multiprocess browser
- 1 browser process
- Multiple rendering processes (
renderer
) - Multiple plug-in processes
- 1
GPU
process - One network process
The benefits of multi-process can avoid a single page, a single plug-in crash impact on the entire browser, but also make full use of multi-core advantages, improve browser stability, speed, security.
Process strategy: Multiple tabs and domain names may be merged into one render process. Through the… -> More Tools -> Task Manager opens the panel.
A process is an independent resource allocated by the system. It is the basic unit of CPU resource allocation. A process is composed of one or more threads. Thread is the execution flow of the process, which is the basic unit of CPU scheduling and dispatching. Multiple threads in the same process share the resources of the process.
Interprocess interaction (during web page loading)
- Browser processReceived user input
URL
Request, determine whether it’s a keyword orURL
(Keyword jumps to default search engine search), then will theURL
Forwarded toNetwork processInitiate a real request (interprocess communicationIPC
). - After receiving the requested data, the network process parses the response header data and forwards it to the browser process, which then sends an “acknowledgement navigation” message to the renderer process.
- After receiving the message, the renderer process establishes a data pipeline with the network process and begins to prepare to receive HTML data. When ready, the renderer sends a “confirm submit” message to the browser process, which begins removing the old document and updating the page state in the browser process.
- Once the document is submitted, the renderer process begins page parsing and subresource loading. When the page is rendered, the renderer process sends a message to the browser process to finish processing.
Browser kernel: rendering process/layout engine/browser engine/page rendering engine/template engine (Blink/Webkit, etc.)
GUI
The render thread- Responsible for rendering pages, parsing
HTML
.CSS
Constitute aDOM
Trees, etc., are invoked when a page is redrawn or when backflow is caused by some operation - and
JS
Engine threads are mutually exclusive whenJS
While the engine thread is working,GUI
The render thread will be suspended,GUI
Updates are placed inJS
Task queue, waitingJS
Execution continues when the engine thread is idle
- Responsible for rendering pages, parsing
JS
Engine threads (e.gv8
Engine, etc.)- Single threaded work, is responsible for
JavaScript
Translate to CPU instructions (Machine code
) - and
GUI
Render threads are mutually exclusive,JS
Running too long will cause the page to block - A browser
Tab
(renderer
There is only one processjs
The thread running - See more on how the V8 engine works below
- Single threaded work, is responsible for
- Event trigger thread
- Control the event loop, manage a task queue/event queue, asynchronous task trigger condition is reached, put callback events into the task queue
- When an event that meets the trigger condition is fired, the thread adds the corresponding event callback function toTask queueAt the end of the line, waiting
JS
Engine processing
- Timer trigger thread
setInterval
与setTimeout
The thread- The reason we have separate threads is because
JS
Engine congestion causes inaccurate timing - Start the timer trigger thread to time and trigger the time, the time will be added to the task queue, waiting
JS
Engine processing
- asynchronous
http
Request thread- Every time
http
When askedStart a new request thread - After the request completes, the callback function is added to the task queue and waits
JS
Engine processing
- Every time
- Synthesis of the thread
- in
GUI
Render thread after execution willGUI
The list to draw generated by the render thread is converted to a bitmap
- in
- IO thread
- Used to communicate with other processes
The browser kernel is mainly divided into:
Its kernel
: apple KHTML based development, open source, used in Safari, also use before Google Chrome, composed of WebCore and JavaScriptCore;Blink kernel
: is a branch of Webkit, developed by Google, currently used in Google Chrome, Edge, Opera, etc.
JS engines are mainly divided into:
SpiderMonkey
: First JavaScript engine, developed by Brendan Eich (aka JavaScript author)Chakra
: Developed by Microsoft for IT browserJavaScriptCore
JavaScript engine in WebKit, developed by AppleV8
Google’s powerful JavaScript engine also helps Chrome stand out from the crowd
web workers
- Principle:
JS
The engine requests a new one from the browserThe child threadAnd passes through the child threadpostMessage API
Communication, the child thread is completely controlled by the main thread - Function: the background runs the calculation, sends the result to the main thread, solves the single thread
JS
The engine does intensive calculations that clog up the page - Child threads cannot affect the user interface, that is, cannot operate
dom
Etc, in a new global context - In addition to
webworker
(belong torenderer
Progress) andSharedWorker
(Multiple tabs,iframe
Share, do not belong to arenderer
A process is itself a process),Service Workers
.ChromeWorker
等 - More refer to 1, refer to 2
Network based
User input url, the browser cache after examination, a DNS query to the corresponding IP (application layer), based on the IP to find the target server (network layer), find the server hardware interface through Mac address (data link layer), and then through the network to the server hardware such as wifi interface transmission bit information (physical layer), The TCP connection (transport layer) is established. If HTTPS is used, SSL (session layer and presentation layer) is established. After the establishment, HTTP requests are sent (application layer).
Reception on the server is the reverse step.
Seven-layer Internet Protocol Stack (ISO)
- Application layer (HTTP, FTP, DNS) This layer provides the interface for the operating system or network applications to access network services, such as DNS resolution into IP and sending HTTP requests
- Presentation layer (Telnet,SNMP) mainly deals with the representation of information exchanged in two communication systems, including data format exchange, data encryption and decryption, data compression and terminal type conversion, etc
- Session layer (DNS,SMTP) This layer manages the session process between hosts, that is, it is responsible for establishing, managing, and terminating the session between processes, such as controlling the login and logout process (QoS).
- Transport layer (TCP, UDP) Establishes TCP/UDP connections. The units of data are called segments.
- Network layer (IP,ARP) IP address, the unit of data is called packet (router, layer 3 switch)
- Data Link layer (PPP) encapsulates bit streams as Frame frames (bridge, Layer 2 switch, Ethernet)
- Physical layer (transmit BIT stream) Physical transmission (transmit through twisted pair, electromagnetic wave, optical fiber, repeater, hub, network cable interface and other media)
- IP addressing algorithms include RIP, which has the minimum IP route forwarding times and is suitable for small networks, and OSPF, which has the highest IP route forwarding speed and is suitable for large networks.
- ARP protocolIs one through parsing
IP
Address to findMac
Address protocol,IP
Address translationMac
After the address, Ethernet data can be transmitted. - EthernetIt belongs to the data link layer, which is mainly responsible for the communication between adjacent devices. The principle is to query the switch
Mac
Table, find the physical interface of the communication parties, and then start the communication.
DNS
A URL generally consists of several parts:
protocol
, protocol headers, such as HTTP, FTP, etchost
, host domain name or IP addressport
And the port numberpath
, directory pathquery
, that is, query parametersfragment
, i.e.,#
Hash value, usually used to locate a location
Uris are uniform resource identifiers and urls are uniform resource locators. Every URL is a URI, but not every URI is a URL. For example, URI: mailto: [email protected]
If you enter a Domain Name, the Domain Name System (DNS) resolves the entered Domain Name into an IP address, that is, Domain Name resolution. DNS is a distributed database that maps domain names to IP addresses. Search for the corresponding IP address based on the following priorities:
- Browser cache
- Native cache (
host
Files, etc.) - Local domain name Resolution server (China Telecom, China Unicom and other operators)
DNS
Root DNS server,DNS
Two root DNS servers
If static resources are requested, traffic may reach the CDN server. If the request is for a dynamic resource, the situation becomes more complicated and the traffic may go through proxy/gateway, Web server, application server, and database in sequence.
DNS resolution is time-consuming. If too many domain names are resolved, the first screen load becomes slow. Therefore, you can use dnS-Prefetch optimization. Reduce domain name DNS resolution time to improve web page loading speed to a new level
TCP
With an IP address, the client and server establish a TCP connection before the HTTP request. TCP is a full-duplex, connection-oriented, reliable, byte stream – based transport-layer communication protocol.
Noun explanation
- SYN(synchronous establishing online) Synchronous sequence number
- Acknowledgement code
- PSH transfer (push)
- FIN (finish)
- RST reset (reset)
- URG (urgent urgent)
- Sequence Number (SEQ Sequence number) Last ACK of the peer (SEQ is randomly generated by the system for the first time)
- Acknowledge number Acknowledge number The recipient’s SEq +1 (when no data is transmitted) or seq+L (length of message L)
The three-way handshake
The purpose of the three-way handshake is to connect to a specified port on the server, establish a TCP connection, synchronize the serial number and confirmation number of the two connected parties, and exchange TCP window size information. In socket programming, a client executing connect() triggers a three-way handshake.
- Client send
The SYN packet
(SYN=1,seq=x,x is a random number) packets to the server and enterSYN_SEND
State; - Server received
The SYN packet
After that, send oneACK packet
(ACK number=x+1,ACK=1) confirm and send one of its ownThe SYN packet
(SYN=1, seq=y), i.eThe SYN + ACK packet
, the server entersSYN_RCVD
State; - The client receives
The SYN + ACK packet
After that, send oneACK packet
(ACK number=y+1, ACK=1) Confirm. The client enters after sending the packetESTABLISHED
The server enters the status after receiving the packetESTABLISHED
State completes the three-way handshake
Once the connection is established, the data is transferred.
Four wave steps
Either the client or the server can initiate the wave action actively. In socket programming, either side performs the close() operation to generate the wave action. Suppose the client wants to close the connection:
- The client sends a message to the server
FIN = 1, seq = x
Package, indicating that the client actively wants to close the connection and then enterFIN_WAIT_1
State. (The client can no longer send data to the server, but can read it.) - Server received
FIN
After the packet is sent to the clientACK = 1, ACKnum = x + 1
Confirm the package and enterCLOSE_WAIT
State. (The server can no longer read the data, but can continue to send data to the client. At the same time, the client receives the confirmation packet and entersFIN_WAIT_2
State). - The server finishes sending dataTo the client
FIN = 1, seq = y
Package, then enterLAST_ACK
Status, waiting for the client to return the last oneACK
The package. After that, the server can neither read nor send data. - The client receives
FIN
After the packet is sent to the serverACK = 1, ACKnum = y + 1
Confirm the package and enterTIME_WAIT
State, then wait long enough (2MSL
), did not receive the serverACK
, thinking that the server has closed the connection normally, so they close the link to enterCLOSED
To release network resources.
Note: The second and third waves are not sent at the same time. When the server receives a FIN packet, the SOCKET may not be closed immediately. Therefore, the server can only reply an ACK packet to the Client, telling the Client that “I received your FIN packet”. I can send FIN packets only after all packets from the server are sent. Therefore, THE FIN packets cannot be sent together.
The SYN attack
Attacking clients forge a large number of non-existent IP addresses in a short period of time, sending SYN packets to the server continuously, and the server replies with acknowledgement packets and waits for the client’s confirmation. Because the source address does not exist, the server needs to continuously resend until timeout. These forged SYN packets occupy the unconnected queue for a long time, and normal SYN requests are discarded, resulting in slow running of the target system, or even network congestion and system breakdown in serious cases. SYN attack is a typical DoS/DDoS attack.
Defense:
- Shorten SYN Timeout
- Increase the maximum number of connections
- Filtering gateway Protection
- The SYN cookies technology
TCP KeepAlive
If an ACK message is received from the peer end, the TCP connection is considered alive. If no response is received after a certain number of retries, the TCP connection is discarded.
TCP/IP concurrency limit
- in
HTTP / 1.0
In, a server is finishing sending aHTTP
After the response, the link is disconnectedTCP
Link. But each request will be re-established and disconnectedTCP
Connection, too expensive. - so
HTTP / 1.1
Write the Connection header into the standard (Connection: keep-alive
) and is enabled by defaultA persistent connection
Unless stated in the requestConnection: close
Then the browser and the server will persist for some timeTCP
The connection does not break at the end of a requestSSL
The cost can also be avoided. inchrome
In the browsernetwork
Tags – >connection ID
saidA TCP connection
Reuse. - in
HTTP / 1.1
In a singleA TCP connection
Only one request can be processed at a time, and multiple requests can be processed sequentially. inHTTP2
Due toMultiplexing
Characteristic of the presence of multipleThe HTTP request
Can be in the sameA TCP connection
In parallel. - The browser concurrent to the same domain name
A TCP connection
There are limits (ranging from 2 to 10), Chrome allows up to oneHost
Set up sixA TCP connection
.
Get and POST
get
Secure idempotent, fetching resources from the server;post
向URI
The specified resource submits data and the data is placed in the packetbody
;get
When requested, the browser willheaders
和data
The server responds with 200 to send back data (send onetcp
Data packet);post
The browser sends the request firstheaders
, server response100 continue
, and the browser sends itdata
In response to 200, the server returns data (sending twotcp
Packet).
The difference between TCP/UDP
- TCP is connection-oriented and UDP is connectionless. TCP establishes a connection with the peer through the three-way handshake mechanism before communication, whereas UDP sends data to the peer without establishing a connection
- The TCP connection takes time, but UDP does not
- TCP connection delays increase the possibility of attacks, but UDP does not require connections and has higher security
- TCP is reliable to ensure the correctness of data transmission and not easy to lose packets. UDP is unreliable and prone to packet loss
- TCP has a slow transmission rate and poor real-time performance, while UDP has a fast transmission rate. TCP connection establishment requires time, and TCP header information is too much, each transmission of useful information is less, poor real-time
- TCP is in stream mode, and UDP is in packet mode. TCP can continuously send data to the buffer as long as it does not exceed the size of the buffer. The receiving end can read multiple data packets at a time as long as there is data in the buffer. Udp can read only one data packet at a time and each data packet is independent
Six methods of TCP reliability
- Sequential numbering: When transferring a file, TCP divides the file into multiple TCP packets (HTTP request messages are too long). Each full packet is about 1 KB in size. To ensure reliable transmission, TCP numbers these packets in sequence
- Acknowledgement mechanism: When the successful packet is sent to the receiver, the receiver will send the sender a successful ACK signal according to TCP, which contains the serial number of the current packet (stop waiting protocol ARQ)
- Timeout retransmission: When the sender sends a packet to the receiver, a timer is set for each packet. If the sender does not receive the ACK signal from the receiver within the set time, it will send the packet again until it receives the ACK signal from the receiver or the connection is disconnected (stop waiting protocol ARQ).
- Check information: The TCP header has more check information and the UDP header has less check information
- Flow control: Packets can be lost if the sender sends data too fast for the receiver to receive. In order to avoid packet loss, it controls the sending speed of the sender so that the receiver can receive the packet in time. This is flow control. Implemented by the sliding window protocol (continuous ARQ protocol). The sliding window protocol not only ensures error-free grouping and orderly receiving, but also realizes flow control. The main way is that the ACK returned by the receiver will contain the size of its own receive window, and use the size to control the data sent by the sender
- Congestion control: Congestion control works on the network to prevent too much data from being injected into the network. Common methods are: slow start, avoid congestion; Fast retransmission, fast recovery
HTTP
After the TCP three-way handshake is complete, HyperText Transfer Protocol (HTTP) requests are sent.
- HTTP’s most prominent advantages are simplicity, flexibility and ease of extension, wide application, and cross-platform.
- HTTP’s biggest double-edged sword is stateless, plaintext transport.
- The biggest disadvantage of HTTP is that it is not secure.
HTTP workflow
- Address resolution
- Encapsulates HTTP request packets
- Encapsulate a TCP packet and establish a TCP connection (TCP three-way handshake)
- The client sends a request command
- Server response
- The server closes the TCP connection
The client wraps the request into HTTP packets –> Tcp packets –> Ip packets –> data frames –> hardware converts the frames into a bit stream (binary data) –> finally sends the request through physical hardware (nic chip) to the specified location.
The server hardware first receives a bit stream, which is converted into data frames, and then into IP packets. Then the IP packet is parsed through IP protocol, and then the TCP packet is parsed through TCP protocol, and then the HTTP packet is parsed through HTTP protocol to get the data.
HTTP packet Structure
A packet generally includes the General header, request/response header, and request/response body
General head
Request Url
: Requested Web server addressRequest Method
: Request mode (Get, POST, OPTIONS, PUT, HEAD, DELETE, CONNECT, TRACE)Status Code
: Indicates the return status code of the request. For example, 200 indicates successRemote Address
: requested remote server address (converted to IP)Referrer-Policy
: Controls the content of the referrer in the request headerRefer to
For cross-domain rejection, methods may be options, status codes 404/405, etc. (of course, there are many possible combinations)
Method is generally divided into two batches:
HTTP1.0
Three request methods are defined:GET, POST, and HEAD methods
. As well as severalAdditional Request Methods: PUT, DELETE, LINK, and UNLINK
HTTP1.1
Eight request methods are defined:GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE, and CONNECT methods.
The meanings of different ranges of status codes are listed below for more information:
1xx
— Indicates that the request has been received and processing continues2xx
– Success: The request is successfully received, understood, or accepted3xx
Redirect, further action must be taken to complete the request4xx
— Client error, request syntax error or request unfulfilled5xx
The server failed to fulfill a valid request
Request/response headers
Common request headers (parts) :
Accept
: Indicates the MIME type supported by the browserContent-Type
Accept-Encoding
: Indicates the compression type supported by the browser, such as gzipContent-Type
: Type of entity content sent by the clientCookie
: There are cookies and they are automatically carried when the domain is accessedConnection
: How to handle long connections when the browser communicates with the server, such as keep-aliveHost
: Requested server URLOrigin
: Where does the original request originate from (only down to port),Origin has more respect for privacy than RefererReferer
: the source URL of the page (applies to all types of requests and will be exact to the detailed page address, CSRF interception is often used for this field)User-Agent
: Provides necessary information about the user client, such as the UA headerIf-Modified-Since
: http1.0 weak cache, correspondingLast-Modified
Expires
: http1.0 strong caching,If-None-Match
: http1.1 weak cache, correspondingETag
Cache-Control
: http1.1 strong cache
Common response headers (parts) :
Access-Control-Allow-Headers
: Specifies the request Headers allowed by the serverAccess-Control-Allow-Methods
: Request method allowed by the serverAccess-Control-Allow-Origin
: the Origin header allowed by the server (e.g. *)Content-Type
: The type of entity content returned by the serverContent-Length
: Indicates the data length of the responseContent-Encoding
What compression format is used to represent the data returned by the serverDate
: Indicates the time when data is sent from the serverSet-Cookie
: sets the cookie associated with the page. The server passes the cookie to the client through this headerKeep-Alive
If the client has keep-alive, the server will respond (e.g. Timeout =38).Server
: Information about the serverCache-Control
: Tell the browser or other client what environment is safe to cache documents inLast-Modified
: Time when the requested resource was last modifiedExpires
: When should a document be considered expired so that it is no longer cachedETag
: The current value of the request variable’s entity label
In general, request headers and response headers are matched for analysis.
- Request-header
Accept
To and respond to the headerContent-Type
Matches, otherwise an error is reported - In a cross-domain request, the header of the request
Origin
To match the response headerAccess-Control-Allow-Origin
Otherwise, a cross-domain error is reported - When using cache, request header’s
The if-modified-since, If - None - Match
Respectively and the response headerLast-modified, ETag
The corresponding
Request/response entity
- The request entity will put the required parameters in (for POST requests), such as the serialized Form of the parameters in the entity (a=1&b=2), or directly in the Form object (the Form Data object, which can be uploaded with parameters and files), etc
- The response entity is to put the content that the server needs to send to the client. Generally, the current interface request, the entity is the JSON format of the information, and the page request, which is directly put an HTML string, and then the browser itself parses and renders.
Form Data and Request Payload
Post /put Committing:
Content-Type: application/json
When, for theRequest Payload
(json
)Content-Type: application/x-www-form-urlencoded
或multipart/form-data
When, for theForm Data
(string
The format forkey1=value1&key2=value2
, similar toGET
The request ofQueryString
Format)
They are only because of the content-Type setting, not because of the data submission method, both of which place the data in the message-body. Chrome’s developer tools, however, differentiate between displays based on this ContentType.
CRLF
CRLF (Carriage Return line-feed), which stands for Carriage Return Line, usually exists as a delimiter. There is a CRLF delimiter between the request header and the entity message, and a CRLF delimiter between the response header and the response entity
CRLF->Windows-style
LF->Unix Style
CR->Mac Style
Copy the code
HTTP 1.1 performance bottlenecks
- Request/response headers are sent uncompressed, with more headers and more latency. Only the Body part can be compressed;
- Send lengthy headers. Sending the same header each time causes more waste;
- Serial file transfer: the server responds in accordance with the order of requests. If the server responds slowly, the client will not be able to request data all the time, that is, the queue head is blocked.
- No request priority control;
- Requests can only start from the client and the server can only respond passively.
HTTP is different from TCP/IP
TPC/IP
Protocol is a transport layer protocol, which mainly addresses how data is transmitted on the networkHTTP
Is the application layer protocol, mainly to solve how to package dataWEB
useHTTP
Protocol acts as an application-layer protocol for encapsulationHTTP
Text message, then useTCP/IP
Use transport layer protocol to send it to the network.
Long connection and short connection
TCP/IP level:
- Long connection: one
tcp/ip
Multiple packets can be sent consecutively on the connectionA TCP connection
During the hold period, if no data packet is sent, both parties need to send detection packets to maintain the connection. Generally, they need to do online maintenance (similar to heartbeat packets). - Short connection: a short connection is established when there is data interaction between two communication parties
A TCP connection
After the data is sent, the link is disconnectedA TCP connection
HTTP level:
http1.0
By default, short connections are used, that is, every time the browser makes a connectionhttp
Operation, establish a connection once, break the connection at the end of the task, such as each static resource request is a separate connection.http1.1
The default is to use a long connection, which will have this lineConnection: keep-alive
In the long connection case, when a web page is opened, the client and the server are used for transmissionhttp
的A TCP connection
Does not close, if the client visits the server’s page again, it will continue to use the established connection.
Note: Keep-alive does not last forever. It has a duration and is usually configured on the server (such as Apache). Keep-alive only works when both the client and the server support the keep-alive connection.
The HTTP 2.0
- multiplexing(instead of http1.x sequence and blocking mechanism, all communication with the domain name is completed on a single TCP connection, eliminating the delay and memory consumption caused by multiple TCP connections; In addition, requests and responses can be interleaved in parallel on a single connection without interference. A lot of
http1.1
There is no need to use optimization solutions (such as packaging into Sprite maps, static resources multi-domain splitting, etc.) - The first compression(
http
Head compression (HPACK algorithm), reduce volume) - Binary frame splitting (a binary frame splitting layer is added between the application layer (HTTP/2) and the transport layer (TCP or UDP) to improve the transmission performance and achieve low latency and high throughput)
- Server-side Push (also known as Cache Push Cache). The server can send multiple responses to a request from the client and actively notify the client. When a client requests resource X and the server knows that it probably also needs resource Z, the server can send the request before the client sends the request. Actively push resource Z to the client)
- Request priority (If a data stream is assigned a priority, it is processed based on that priority, with the server deciding how many resources it needs to process the request.)
The HTTP 3.0
Http2 multiplex relationship, in the case of packet loss, the whole TCP will start to wait for retransmission, which leads to all the data behind the block, so instead of http1 performance, so Google more started to make a UDP protocol based on QUIC protocol, that is, HTTP3.
New QUIC features include:
- 0-RTT: similar to THE TCP quick open technology, caches the context of the current session. In the next session recovery, the server only needs to transfer the previous cache to the server for verification. 0RTT connection is arguably QUIC’s biggest performance advantage over HTTP2.
- True · Multiplexing: QUIC is udP-based, there are no dependencies between multiple streams on a connection, and there is no TCP queue header blocking. QUIC will also perform better on mobile than TCP. Because TCP identifies connections based on IP and port, this approach is vulnerable in the volatile mobile network environment. But QUIC identifies a connection by ID, so no matter how your network environment changes, as long as the ID stays the same, you can reconnect quickly.
- Encrypted authentication packets: Except for a few packets, such as PUBLIC_RESET and CHLO, all headers of packets are authenticated and the Body of packets is encrypted.
- Forward error correction mechanism (FEC) : Each packet contains part of the data of other packets in addition to its own contents, so a small number of lost packets can be directly assembled from the redundant data of other packets without retransmission. Forward correction sacrifices the upper limit of how much data can be sent per packet, but reduces retransmission due to packet loss, because retransmission takes more time.
HTTPS
The difference between HTTPS and HTTP is that an SSL link is established before a request is made to ensure that subsequent communication is encrypted and cannot be easily intercepted and analyzed.
HTTPS Principle (SSL four-way handshake)
In general, the main focus is on the SSL/TLS handshake flow:
-
ClientHello
The browser initiates an HTTPS request to establish an SSL link (port 443 of the server) and sends the following information to the server (the first HTTP request, or plaintext transmission) :
- The random number
Client random
, followed by the generationSession symmetric encryption key
- Client supported
Encryption methods
, such as RSA encryption - Client supported
SSL/TLS
Protocol version, such as TLS 1.2
- The random number
-
SeverHello
After receiving the request from the client, the server sends the following message (in plaintext) to the client:
- The random number
Server random
, followed by the generationSession symmetric encryption key
- To confirm the
The encryption algorithm
withThe Hash algorithm
- confirm
SSL/ TLS
Protocol version. Disable encrypted communication if the browser does not support it - The server’s
The digital certificate
(The certificate contains information such as the website address, asymmetrically encrypted public key, and certificate authority)
- The random number
-
Browser response
TLS to verify the validity of the certificate (via a browser or issued by the CA public key authentication mechanism is legal in the operating system, whether certificate contained in the site and are accessing, expiration date, etc.), if the certificate trust the browser will display a small locks, otherwise it will pop up a warning message certificate problems.
When the client receives the certificate (untrusted), it extracts the server’s public key from the digital certificate and uses it to encrypt the message to send the following message to the server (second HTTP request) :
- New random number
Premaster secret
, the random number will be encrypted by the server public key - Notification of encrypted communication algorithm change, indicating that subsequent messages will be encrypted with the session key.
- Notification indicating that the client handshake is over. This entry also makes a summary of all previous content occurrence data for the server to verify.
Client Random, Server Random and Premaster Secret are used to generate the session symmetric encryption key of this communication through the encryption algorithm negotiated by both parties.
- New random number
-
Final response from the server
After receiving the third random number Premaster secret from the client, the server calculates the session symmetric encryption key of this communication through the negotiated encryption algorithm. Use this key to decrypt the handshake message sent by the browser and verify that the Hash is the same as that sent by the browser. The final message is then sent to the client:
- Notification of an encrypted communication algorithm change, indicating that subsequent messages will be encrypted with the session symmetric encryption key.
- Notification indicating that the server handshake is over. This entry also makes a summary of all the previous content of the occurrence of the data, used for client verification.
-
The browser decrypts and computes the HASH of the handshake message. If the HASH is the same as that sent by the server, the handshake is complete. Next, the client and server enter encrypted communication using the plain HTTP protocol, but with the session-symmetric encryption key.
HTTPS encryption is at the transport layer
HTTPS packets are encrypted when they are packaged as TCP packets. Both the HEADER field and the body field are encrypted.
If you use TCP layer tools such as tcpdump and Wireshark to capture packets, you can obtain the encrypted content. If you use application layer tools such as Charels(Mac) and Fildder(Windows) to capture packets, you can certainly see the clear text.
Encryption algorithm, information digest, digital signature, digital certificate, CA
- Symmetric encryption algorithm:
AES, RC4, 3DES
. - Asymmetric encryption algorithm:
RSA, DSA/DSS
. - Abstract The algorithm (hashing
hash
Algorithm, hash algorithm) :MD5, SHA1, SHA256
, saltsalt
Increase complexity - Message digest: The original message digest is a fixed-length message digest using the HASH algorithm
- Digital signature: Ciphertext in which the message digest is encrypted by the private key
- Digital certificates: Can be simply understood as recognized by a CA and cannot be tampered withThe public key, can be used to verify that a website is trustworthy (for
HTTPS
), verify whether a file is trusted (whether it has been tampered with), or use one certificate to prove that another certificate is authentic. The top-level certificate is called the root certificate. Except for the root certificate, which proves itself to be reliable, all other certificates rely on the certificate of the higher level to prove itself. CA
: Certificate Authority The Authority that issues a Certificate- The root
CA ` ` : CA
的CA
, can be issuedCA
The certificate of - Root certificate: root
CA
Self-signed certificates, built into the operating system and browser
The difference between HTTPS and HTTP
http
The information is transmitted in clear text, the connection is simple and stateless,https
Is a secure encrypted transmission.http
Is directly withTCP
For data transmission,https
It’s through one levelSSL
(OSI session layer), port former is80
, which is443
.https
The protocol handshake phase is time-consumingca
Applying for certificates or homemade certificates can increase page load time by nearly 50% and increase power consumption by 10% to 20%.https
Connection cache is not as good ashttp
High efficiency, increasing data overhead and power consumption, even affecting existing security measures.- In August 2014, Google changed its search engine algorithm, saying, “It is better than the same
HTTP
Website, usingHTTPS
Encrypted sites will rank higher in search results.
COOKIE
Cookie is a local storage mode of the browser. It is generally used to help the communication between the client and the server, and is often used for identity verification, combined with the session of the server.
The scenario is as follows:
In the login page, when the user logs in, the server will generate a session, which contains information about the user (such as user name, password, etc.), and then there will be a sessionID (equivalent to the key corresponding to the session on the server). When the server returns data, it sets the browser’s local cookie value to jsessionID = XXX. When visiting pages under the same domain name in the future, cookies will be automatically brought to verify that there is no need to log in again within the valid time.
A cookie is briefly
GZIP compression
First of all, it is clear that GZIP is a compression format, which requires browser support to be effective (but generally now browsers support), and gZIP compression efficiency is very good (up to 70% or so), generally enabled by Apache, Tomcat and other Web servers, generally only need to enable gZIP compression on the server. Then all subsequent requests are based on gzip compression, although the server may have other compression formats besides Gzip (such as Deflate, which is less efficient and less popular).
Background processing
Load balancing
User initiated the request to the scheduling server (the reverse proxy server, such as install nginx control load balancing), and then according to the actual scheduling algorithm, scheduling server distribution of different requests to correspond the cluster server, and then the scheduler wait for actual server HTTP response, and feedback to the user.
Background processing
- The container receives the request (e.g., the Tomcat container) through unified validation such as security interception, cross-domain validation. If it does not meet the rules, it directly returns the corresponding HTTP packet (such as rejecting the request).
- After the validation passes, it enters the actual background code (such as a Java program), at which point the program receives the request and executes it (such as database queries, bulk calculations, and so on)
- After the program is executed, it will return an HTTP response package (generally, this step will also go through multi-layer encapsulation) and send it to the front end to complete the interaction
The front-end cache
For a data request, it can be divided into three steps: initiating a network request, back-end processing and browser response. Browser caching helps us optimize performance in the first and third steps.
- Each time the browser initiates a request, it first looks up the result of the request and the cache identifier in the browser cache
- Each time the browser receives the result of the returned request, it stores the result and the cache id in the browser cache
Cache location priority
Service Worker
Memory Cache
Disk Cache (HTTP Cache)
Push Cache
Do not get the formal network request to request the latest data.
Service Worker
A Service Worker is a separate thread running behind the browser and the transport protocol must be HTTPS. Unlike other built-in caching mechanisms in browsers, it gives us control over which files to cache, how to match the cache, and how to read the cache, and the cache is persistent.
Implementation steps:
- registered
Service Worker
And then listen ininstall
The required files can be cached after the event - The next user can intercept the request to check whether the cache exists. If the cache exists, the user can directly read the cache file
- If there is no cache hit, call
fetch
Function retrieves data by cache priority, regardless of where the data is coming from at this pointnetWork
里size
Will be displayed asService Worker
Memory Cache
- The in-memory cache, in which almost all network requests are automatically added by the browser
memory cache
Medium, short-term storage (preload) - The browser TAB is closed
memory cache
Then the failure - Ignore HTTP headers from
memory cache
When obtaining cache contents, browsers ignore header configurations such as max-age=0 and no-cache - but
Cache-control:no-store
It’s an exceptionmemory cache
failure
Disk Cache
A Disk Cache (HTTP Cache) is a Cache stored on a hard Disk. It is slower to read, but everything can be stored on Disk, which is better than Memory Cache in terms of capacity and storage timeliness.
Strong cache
Mandatory cache (200 from cache), when the client requests, the cache database is accessed first to see if the cache exists. If present, return directly; If it does not exist, request the real server and write the response to the cache database. Forcing the cache to directly reduce the number of requests is the cache strategy that improves the most.
- Http1.0:
Expires
Represents the cache expiration time (absolute time), as in:Expires: Thu, 10 Nov 2017 08:45:11 GMT
(Disadvantages: complex writing; Incorrect local time causes errors. - Http1.1:
Cache-control
Represents the maximum valid time (relative time) of the cache, as in:Cache-control: max-age=2592000
(Other values:No - the cache, the no - store, public, private, etc
)
Resources that change frequently: cache-control: no-cache Resources that do not change frequently: cache-control: max-age=31536000
Weak cache
Negotiation cache (304 Not Modified) and comparison cache. After the cache is invalid, the browser sends a request to the server with the cache identifier. The server decides whether to use the cache according to the cache identifier. 304 Not Modified is returned on a hit, 200 is returned on a miss, and the new resource and cache identifier are saved to the browser cache. The number of requests is the same as that without caching, but the response volume is greatly saved (when 304, Network size refers to the size of the server’s communication packets).
- Http1.0:
The last-modified and If - Modified - Since
Determine whether the file is expired according to the modification time, accurate to second. Such as:Last-Modified: Mon, 10 Nov 2018 09:10:11 GMT
- Http1.1:
The ETag and If - None - Match
Determine whether the file is expired based on its content, for example:etag: "FoWFkJxGtx5Edfyku7luLdv_wucA"
Push Cache
Push Cache is HTTP/2 and is used when all three caches fail. It only exists in the Session, is released once the Session ends, has a short cache time (about 5 minutes in Chrome), and does not strictly implement the cache instructions in the HTTP header.
Cache processes
- call
Service Worker
的fetch
Incident response - To view
memory cache
- To view
disk cache
- If there is a forced cache and it is not invalidated, the forced cache is used and the server is not requested. The status codes are all
200
- If there is a mandatory cache but it has failed, use a comparative cache and determine after comparison
304
or200
- If there is a forced cache and it is not invalidated, the forced cache is used and the server is not requested. The status codes are all
- Sends a network request and waits for a network response
- Store the response content
disk cache
(ifHTTP
If the header configuration can be saved) - Store a reference to the response content
memory cache
(ignoringHTTP
Configuration of header information) - Store the response content
Service Worker
的Cache Storage
(ifService Worker
The script is calledcache.put()
)
Browser behavior
- Open the web page, the address bar enter the address: search
disk cache
Is there a match in. Use if available; If no network request is sent. - Plain refresh (F5) : Because TAB is not closed, so
memory cache
Is available and will be used preferentially (if matched). The second is thedisk cache
. - Forced refresh (Ctrl + F5) : The browser does not use caching, so requests are sent with a header
Cache-control: no-cache
(And for compatibilityPragma: no-cache
), the server returns 200 and the latest content.
Page rendering process
After the browser gets the HTML and other resources, it parses and renders the HTML. You can view the parsing process on the Chrome console ->Performance->EventLog.
The process is briefly
After the browser kernel gets the content, the rendering steps are divided into the following steps:
- (DOM) parsing
HTML
Content isDOM
树 - (Recalculate Style) will be
CSS
convertstyleSheets
And calculateDOM
Node style - Generate the population Tree (render Tree) and calculate the Layout information of the elements
- (Layer Tree) Layers the layout Tree (render Layer) to generate the Layer Tree
- (Paint) Generates a draw list for each layer and submits it to the composition thread
- (Tiles/raster) divide the layer into Tiles and convert the Tiles into bitmaps in the raster thread pool
- (Composite Layers) Merge the layers to form an image and save it
GPU
In the memory - (DrawQuad) the browser process reads
GPU
Memory to display web pages
The first five steps are in the render thread, six and seven steps are in the compositing thread, and the last step is in the browser process.
HTML parsing, build DOM tree
Namely: byte -> character -> token -> node object -> Object model:
- Decode: The browser converts the obtained HTML content (Bytes) into a single character based on its encoding
- Tokenization: The browser converts these characters into different token tokens according to the HTML specification, each with its own unique meaning and set of rules
- Lexical analysis: The generated token is transformed into an object (node object) that defines its properties and rules
- DOM construction: When the DOM tree is built, the entire object collection is like a tree structure
The DomContentLoaded event is triggered when the DOM tree is built and the HTML referenced javascript code is synchronized (not including style sheets and images). Has nothing to do with the order in which async loaded the scripts, but must be loaded after defer script execution.
jQuery $(document).ready(()=>{}); The DOMContentLoaded event that listens on.
Parses CSS and performs style calculations
- Formatting style sheets: Similar to HTML parsing, that is:
Bytes → characters → tokens → nodes → CSSOM
,StyleSheets (CSSOM)
. throughdocument.styleSheets
View the results - Standardized style sheets: for example
Em - > px, red - > rgba (255,0,0,0), bold - > 700
- Calculate each
DOM
Node style: Passinheritance
和cascading
, completes the calculation of the specific style of each element in the DOM node. throughwindow.getComputedStyle
View the results
Render Tree Render Tree
- The browser Layout system requires an additional Layout Tree that contains only visible elements (head, meta, display: None, which are not visible in the DOM Tree).
- Computes the coordinate positions of nodes in the layout tree
layered
-
Generate Layer Tree
Each node in the DOM tree corresponds to a LayoutObject. When their LayoutObject is in the same coordinate space, a Render layer is formed.
Chrome -> More Tools -> Layer View Layer information
-
The rendering engine creates separate layers (composite/composite) for specific nodes.
Some special rendering Layers are considered Compositing Layers, which have a separate GraphicsLayer and allocate resources separately, so it is also called enabling GPU hardware acceleration. Other rendering layers that are not composite layers share the same layer as their first parent layer that has GraphicsLayer.
- (explicit composition) haveCascading contextAttribute elements are promoted to a separate layer:
HTML root element; opacity; isolation; will-change; video,canvas,iframe; position:fixed; Transforms: Translate3D, translateZ, etc
- (Explicit composition) requires clipping (
clip
) will also create layers: for example, if a label is small,50 * 50
Pixels, you put a lot of text in there, and the extra text has to be cropped; If a scroll bar is present, the scroll bar will also be promoted to a separate layer - (Implicit composition)
z-index
Lower nodes are promoted to a separate layer, and nodes with higher levels of hierarchy become separate layers
Chrome -> More Tools -> Rendering -> Layer Borders: yellow is the compound Layer information.
- (explicit composition) haveCascading contextAttribute elements are promoted to a separate layer:
Advantages and disadvantages of synthetic layer and suggestions:
- Optimal: 1. The ratio
cpu
Fast processing (i.eGPU hardware acceleration
) 2.repaint
Does not affect other layers 3. YesDirect synthesis - Bad: a large number of synthetic layers will make the transfer to
GPU
Slow down and take upGPU
And memory resources will also appearLayer explosion
- Suggestion: Use animation
transform
Implementation; Reduce implicit composition; Reduce the size of the composite layer
Layer to draw
Once the layers have been built, the rendering engine breaks down a complex layer into small instructions, which are then followed by a list of instructions to draw.
In Chrome -> More Tools -> Layer-profiler, you can see the list drawing process on the right.
rasterize
Rasterization/rasterization (RAster) : Blocks generate bitmaps.
When the layer’s drawing list is ready, the render thread commits the drawing list to the composition thread. The compositing thread divides the layer into tiles and generates bitmaps in preference to tiles near the viewport. The rendering process maintains a rasterized thread pool in which all rasterization of blocks is performed (this means in browsers without hardware acceleration enabled, i.e., CPU software rendering).
Fast rasterization, GPU rasterization: In general, the rasterization process uses GPU to accelerate generation. In the rendering process, the instruction of bitmap generation is uploaded to GPU as texture through shared memory through GraphicsContext (GraphicsLayer has a GraphicsContext) for GPU synthesis. The generated bitmap is stored in GPU memory. Belongs to GPU hardware-accelerated rendering. More introduction
synthetic
What is composition? Compositing is a technique for dividing a page into several layers, rasterizing them separately, and then combining them into a single page in a single thread, the Compositor thread. When the user scrolls the page, all the browser needs to do is compose a new frame and send it to the GPU to show the scrolling effect, since all the layers of the page are rasterized. The page animation implementation is similar by moving the layers on the page and creating a new frame.
When the blocks above the layer are rasterized, the compositor thread collects the information called draw quads from the blocks to construct a Compositor frame.
- Drawing quadrilateral: Contains information such as the location of the blocks in memory and the position of the blocks on the page after the layers are composed
- Composite frame: a collection of drawn quadrilateral frames that represent the contents of a frame on a page (60fps refers to this)
According to
The composite thread submits a render frame to the browser process via IPC. The VIZ component in the browser process is used to receive the DrawQuad command sent by the compositing thread. Then, according to the DrawQuad command, the compositing frame is sent to the GPU for aggregation and the final complete compositing surface is generated. Finally, the memory is sent to the graphics card and finally displayed on the screen.
Graphics: The screen refresh rate is 60 frames, and an image stays around 16.7 ms. Each update comes from the graphics card’s front buffer. The graphics card receives the browser process from the page, will synthesize the corresponding image, and the image saved to the back buffer, and then the system will automatically swap the front buffer and the back buffer, so the cycle update. If a certain animation logic takes up a lot of memory, the browser will generate the image slowly, the image will not be delivered to the graphics card in a timely manner, and the monitor will refresh at the same rate, so there will be a lag, which is a noticeable drop of frames.
Update the view
Reflow
Also called a Layout. Updated the geometry of the element. The need to update a complete rendering pipeline is a key factor affecting browser performance.
- The following triggers backflow:
- Box model attributes trigger relayout (
width,height,padding,margin,display,border-width,border,min-height
) - Location properties and floats also trigger relayouts (
top,bottom,left,right,position,float,clear
) - Changing the text structure inside a node also triggers a relayout (
text-align,overflow-y,font-weight,overflow,font-family,line-height,vertival-align,white-space,font-size
) - Retrieving certain attributes also causes backflow:
Offset Scroll client(Top/Left/Width/Height)
width,height
- Call the
GetComputedStyle (), getBoundingClientRect ()
Or IEcurrentStyle
- Box model attributes trigger relayout (
Most of the optimization in modern browsers is done through the queuing mechanism to update the layout in batches. The browser will put the modification operation in the queue, and at least one browser refresh (i.e. 16.6ms) will clear the queue. When you get operations on the layout information, you force a queue refresh because there may be operations in the queue that affect the return values of those properties or methods, triggering backflow and redraw to ensure that the correct values are returned.
Repaint
Updated the draw attribute of the element: color,border-style,border-radius,visibility,text-decoration,background,background-image,background-position,background-r Epeat,background-size, Outline-color, Outline,outline-style,outline-width,box-shadow, the rendering pipeline is executed directly from the Paint phase.
Direct synthesis
As mentioned in the composite layer above, using the transform to achieve the animation effect, the rendering pipeline starts directly from tiles/raster, which does not occupy the resources of the rendering thread, greatly improving the rendering efficiency. This is why CSS animations are more efficient than JavaScript animations. (Essentially using GPU acceleration to prioritize compositing layers to merge attributes)
Reduce redrawing and reflow
- Use direct composition or redraw properties instead of reflux properties, as in
The transform - > top, left
.visibility->display:none
Etc. - To animate or frequently redraw reflow nodes as separate layers, use
Transform, opacity, filters, will-change
The triggerGPU
Hardware-accelerated direct synthesis - Avoid frequent operations
DOM
And styles, such as willdom
Offline:documentFragment
.display:none
.clone dom
Setting,class
Class, an update - Avoid the use of
table
Layout as far as possibleDOM
The end of the tree changesclass
- Avoid frequently reading properties that cause backflow/redraw
- Avoid setting multiple inline styles,
css
expression
The download of external chain resources
Some resource connections are encountered while parsing THE HTML, and a separate download thread is opened to download the resource.
CSS style resources are encountered
css
Loading does not blockDOM
Tree parsing (when loading asynchronouslyDOM
Build as usual)- But it blocks the layout tree rendering (wait while rendering)
css
Load done, because the layout tree needscss
Information) - Will block the back
js
Script execution - Exception:
media query
The statementCSS
It doesn’t block rendering
JS script resources are encountered
- Block the parsing of the browser. If an external script is found, the parsing will continue after the script is downloaded and executed
HTML
, the PREVIOUSLY parsed DOM is not affected, that is, FP may be advanced - In the case of an inline script, parsing the page DOM will not begin until all scripts on the page have been executed
- You can add
Defer (defer execution)
或Async (asynchronous execution)
Attributes, ordocument.createElement('script')
To avoid congestion.
An IMG image class resource is encountered
- When you encounter images and other resources, it is directly asynchronous download, will not block parsing, directly replace the original SRC place with pictures after downloading.
- Trigger when all the DOM, stylesheets, scripts, and images on the page have been loaded (including asynchronously)
load
Events.
JS engine parsing process
As mentioned earlier, when you encounter a JS script, you wait until it executes.
How the V8 engine works
V8 is a cross-platform Google open source high-performance JavaScript and WebAssembly engine written in C++ for Chrome, node.js, etc. V8 can be run independently or embedded in any C++ application.
js
The source code byLexical analysis (participle tokenize)Decompose the code intoWord yuan (token)And then through theParsing (parse)Convert according to the syntax rulesASTGenerate an abstract syntax tree (AST
) and execution context.- throughThe interpreter IgnitionAccording to the
AST
generateByteCode(Not directly converted to machine code because of its high memory consumption) - The bytecode execution is explained point-by-point by the interpreter Ignition. Hot-spot functions (functions that are called multiple times) are converted into optimized machine code by the TurboFan compiler, improving the performance of the code. If the type changes and the previously optimized machine code does not handle the operation correctly, it is reversely converted to bytecode.
Ultimately, the computer executes CPU machine code.
JIT
JIT-Just In Time compiler. The interpreter interprets the execution of the bytecode and converts the hotspot function’s bytecode to machine code, and caches the converted machine code. So the speed of the whole program can be significantly improved.
JS execution environment
This is the execution context. The js interpreter also maintains an environment Stack (execution Stack/Call Stack/Stack space Call Stack) during runtime. The script is first loaded, which creates the global execution context and pushes it to the top of the environment Stack (it cannot be ejected). When the execution flow enters a function, an execution context is created and pushed to the top of the stack. When the function is finished, it is ejected from the stack and control is returned to the previous execution environment. The top of the environment stack is always the current executing environment.
If the program is ejected from the stack after execution and is not referenced (no closure is formed), the memory used in this function is automatically reclaimed by the garbage handler.
In JS, the execution environment can be abstractly understood as an object, which consists of the following attributes:
- Scope chain (
Scope chain
) - Variable object (
Variable object
–VO
) this
(Context object)
The scope chain
Scope chain, which initializes the interpreter when it enters an execution environment and assigns it to the current execution environment. The scope chain of each execution environment consists of the variable object of the current environment and the scope chain of the parent environment.
In the context of a function, look for a variable foo. If it is found in the VO of the function, use it directly. Otherwise, look in its parent scope chain.
scope
Scope specifies the scope of a variable or function, that is, the scope within which it can be accessed, that is, its accessibility. In practice, the JS kernel solves the problem of scope management of variables and functions through a series of VO/AO and their connection relations.
JavaScript uses lexical scoping, also known as static scoping, which is determined by the position of the code function declaration.
var value = 1;
function foo() {
console.log(value);
}
function bar() {
var value = 2;
foo();
}
bar();
/ / 1
var scope = 'global scope';
function checkscope() {
var scope = 'local scope';
function f() {
return scope;
}
return f;
}
checkscope()();
//local scope
Copy the code
VO with AO
-
VO: Each execution context allocates a variable object, whose properties consist of variable and function declaration. In the function context, parameter lists are also added to VO as attributes. The variable object is closely related to the current scope. Variable objects in different scopes are different from each other. It holds all functions and variables in the current scope.
-
AO: When a function is activated, an activation object is created and assigned to the execution context. The active object is initialized from the special object Arguments. It is then used as VO for variable initialization.
-
In the context of functions: VO === AO
-
In global context: VO === this === global
In general, VO stores variable information (declared variables, functions, arguments, etc.)
A JS interview questions triggered by the thinking
closure
In JavaScript, according to the rules of lexical scope, an inner function can always access the variables declared in its outer function. When an inner function is returned by calling an outer function, the variables referenced by the inner function remain in memory even after the outer function has finished executing. Let’s call this set of variables a closure. For example, if the external function is foo, then the set of variables is called the closure of the foo function.
Javascript closure concept and usage review
This pointer
This is a property of the execution context, the magic this in Javascript
Recycling mechanism
Garbage collection mechanism for V8 engine
CSS related
CSS dictates that each element has its own box model, which is then placed on the page according to the rules.
BFC
Analysis of BFC and Formatting Contexts
In the middle
CSS centered full version
flex & grid
Flex layout summarizes CSS Grid layout
Some of the properties
rem em
em
As afont-size
Represents the font size of the parent element,em
When used as a unit of other properties, represents its own font size.rem
Applies to the root element, relative to the original size (16px), and to the non-root element, relative to the root element font size.
line-height
High line. The value can be:
normal
About 1.2, depending on the font-family of the elementdigital
Line is highDigital * the font size
The length of the
The line height is the length: 16px, for exampleThe percentage
Line is highFont size * percentage
padding/margin
In addition to the normal length (for example, 16px), the value is mainly concerned with the percentage: the inner margin/margin is the percentage x the width of the parent element, which can be used for height adaptation.
position:fixed
The fixed property creates a new cascading context. When the element ancestor’s transform, Perspective, or filter attribute is not None, the container changes its viewport to that ancestor.
box-sizing
box-sizing: content-box; /* Default value, corresponding to standard box model */
box-sizing: border-box; /* For the IE box model, include the padding and border within the defined width and height */
box-sizing: inherit; /* Specify that box-sizing should inherit from the parent element */
Copy the code
other
- JS prototype and prototype chain details
- 10 common front-end cross-domain solutions
- Front-end Security Summary
- Event Loop
- Promise to realize
- Summary of mobile end front-end adaptation solutions