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
  • 1GPUprocess
  • 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)

  1. Browser processReceived user inputURLRequest, determine whether it’s a keyword orURL(Keyword jumps to default search engine search), then will theURLForwarded toNetwork processInitiate a real request (interprocess communicationIPC).
  2. 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.
  3. 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.
  4. 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.)

  • GUIThe render thread
    • Responsible for rendering pages, parsingHTML.CSSConstitute aDOMTrees, etc., are invoked when a page is redrawn or when backflow is caused by some operation
    • andJSEngine threads are mutually exclusive whenJSWhile the engine thread is working,GUIThe render thread will be suspended,GUIUpdates are placed inJSTask queue, waitingJSExecution continues when the engine thread is idle
  • JSEngine threads (e.gv8Engine, etc.)
    • Single threaded work, is responsible forJavaScriptTranslate to CPU instructions (Machine code)
    • andGUIRender threads are mutually exclusive,JSRunning too long will cause the page to block
    • A browserTab(rendererThere is only one processjsThe thread running
    • See more on how the V8 engine works below
  • 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, waitingJSEngine processing
  • Timer trigger thread
    • setIntervalsetTimeoutThe thread
    • The reason we have separate threads is becauseJSEngine congestion causes inaccurate timing
    • Start the timer trigger thread to time and trigger the time, the time will be added to the task queue, waitingJSEngine processing
  • asynchronoushttpRequest thread
    • Every timehttpWhen askedStart a new request thread
    • After the request completes, the callback function is added to the task queue and waitsJSEngine processing
  • Synthesis of the thread
    • inGUIRender thread after execution willGUIThe list to draw generated by the render thread is converted to a bitmap
  • 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 browser
  • JavaScriptCoreJavaScript engine in WebKit, developed by Apple
  • V8Google’s powerful JavaScript engine also helps Chrome stand out from the crowd

web workers

  • Principle:JSThe engine requests a new one from the browserThe child threadAnd passes through the child threadpostMessage APICommunication, 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 threadJSThe engine does intensive calculations that clog up the page
  • Child threads cannot affect the user interface, that is, cannot operatedomEtc, in a new global context
  • In addition towebworker(belong torendererProgress) andSharedWorker(Multiple tabs,iframeShare, do not belong to arendererA 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)

  1. 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
  2. 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
  3. 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).
  4. Transport layer (TCP, UDP) Establishes TCP/UDP connections. The units of data are called segments.
  5. Network layer (IP,ARP) IP address, the unit of data is called packet (router, layer 3 switch)
  6. Data Link layer (PPP) encapsulates bit streams as Frame frames (bridge, Layer 2 switch, Ethernet)
  7. 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 parsingIPAddress to findMacAddress protocol,IPAddress translationMacAfter 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 switchMacTable, 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, etc
  • host, host domain name or IP address
  • portAnd the port number
  • path, directory path
  • query, that is, query parameters
  • fragment, 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:

  1. Browser cache
  2. Native cache (hostFiles, etc.)
  3. Local domain name Resolution server (China Telecom, China Unicom and other operators)
  4. DNSRoot DNS server,DNSTwo 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.

  1. Client sendThe SYN packet(SYN=1,seq=x,x is a random number) packets to the server and enterSYN_SENDState;
  2. Server receivedThe SYN packetAfter 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_RCVDState;
  3. The client receivesThe SYN + ACK packetAfter that, send oneACK packet(ACK number=y+1, ACK=1) Confirm. The client enters after sending the packetESTABLISHEDThe server enters the status after receiving the packetESTABLISHEDState 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:

  1. The client sends a message to the serverFIN = 1, seq = xPackage, indicating that the client actively wants to close the connection and then enterFIN_WAIT_1State. (The client can no longer send data to the server, but can read it.)
  2. Server receivedFINAfter the packet is sent to the clientACK = 1, ACKnum = x + 1Confirm the package and enterCLOSE_WAITState. (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_2State).
  3. The server finishes sending dataTo the clientFIN = 1, seq = yPackage, then enterLAST_ACKStatus, waiting for the client to return the last oneACKThe package. After that, the server can neither read nor send data.
  4. The client receivesFINAfter the packet is sent to the serverACK = 1, ACKnum = y + 1Confirm the package and enterTIME_WAITState, 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 enterCLOSEDTo 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

  • inHTTP / 1.0In, a server is finishing sending aHTTPAfter the response, the link is disconnectedTCPLink. But each request will be re-established and disconnectedTCPConnection, too expensive.
  • soHTTP / 1.1Write the Connection header into the standard (Connection: keep-alive) and is enabled by defaultA persistent connectionUnless stated in the requestConnection: closeThen the browser and the server will persist for some timeTCPThe connection does not break at the end of a requestSSLThe cost can also be avoided. inchromeIn the browsernetworkTags – >connection IDsaidA TCP connectionReuse.
  • inHTTP / 1.1In a singleA TCP connectionOnly one request can be processed at a time, and multiple requests can be processed sequentially. inHTTP2Due toMultiplexingCharacteristic of the presence of multipleThe HTTP requestCan be in the sameA TCP connectionIn parallel.
  • The browser concurrent to the same domain nameA TCP connectionThere are limits (ranging from 2 to 10), Chrome allows up to oneHostSet up sixA TCP connection.

Get and POST

  • getSecure idempotent, fetching resources from the server;postURIThe specified resource submits data and the data is placed in the packetbody;
  • getWhen requested, the browser willheadersdataThe server responds with 200 to send back data (send onetcpData packet);
  • postThe browser sends the request firstheaders, server response100 continue, and the browser sends itdataIn response to 200, the server returns data (sending twotcpPacket).

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

  1. Address resolution
  2. Encapsulates HTTP request packets
  3. Encapsulate a TCP packet and establish a TCP connection (TCP three-way handshake)
  4. The client sends a request command
  5. Server response
  6. 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 address
  • Request 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 success
  • Remote 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.0Three request methods are defined:GET, POST, and HEAD methods. As well as severalAdditional Request Methods: PUT, DELETE, LINK, and UNLINK
  • HTTP1.1Eight 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 continues
  • 2xx– Success: The request is successfully received, understood, or accepted
  • 3xxRedirect, further action must be taken to complete the request
  • 4xx— Client error, request syntax error or request unfulfilled
  • 5xxThe 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 gzip
  • Content-Type: Type of entity content sent by the client
  • Cookie: There are cookies and they are automatically carried when the domain is accessed
  • Connection: How to handle long connections when the browser communicates with the server, such as keep-alive
  • Host: Requested server URL
  • Origin: Where does the original request originate from (only down to port),Origin has more respect for privacy than Referer
  • Referer: 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 header
  • If-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 server
  • Access-Control-Allow-Methods: Request method allowed by the server
  • Access-Control-Allow-Origin: the Origin header allowed by the server (e.g. *)
  • Content-Type: The type of entity content returned by the server
  • Content-Length: Indicates the data length of the response
  • Content-EncodingWhat compression format is used to represent the data returned by the server
  • Date: Indicates the time when data is sent from the server
  • Set-Cookie: sets the cookie associated with the page. The server passes the cookie to the client through this header
  • Keep-AliveIf the client has keep-alive, the server will respond (e.g. Timeout =38).
  • Server: Information about the server
  • Cache-Control: Tell the browser or other client what environment is safe to cache documents in
  • Last-Modified: Time when the requested resource was last modified
  • Expires: When should a document be considered expired so that it is no longer cached
  • ETag: The current value of the request variable’s entity label

In general, request headers and response headers are matched for analysis.

  • Request-headerAcceptTo and respond to the headerContent-TypeMatches, otherwise an error is reported
  • In a cross-domain request, the header of the requestOriginTo match the response headerAccess-Control-Allow-OriginOtherwise, a cross-domain error is reported
  • When using cache, request header’sThe if-modified-since, If - None - MatchRespectively and the response headerLast-modified, ETagThe 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/jsonWhen, for theRequest Payload (json)
  • Content-Type: application/x-www-form-urlencodedmultipart/form-dataWhen, for theForm DatastringThe format forkey1=value1&key2=value2, similar toGETThe request ofQueryStringFormat)

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/IPProtocol is a transport layer protocol, which mainly addresses how data is transmitted on the network
  • HTTPIs the application layer protocol, mainly to solve how to package data
  • WEBuseHTTPProtocol acts as an application-layer protocol for encapsulationHTTPText message, then useTCP/IPUse transport layer protocol to send it to the network.

Long connection and short connection

TCP/IP level:

  • Long connection: onetcp/ipMultiple packets can be sent consecutively on the connectionA TCP connectionDuring 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 partiesA TCP connectionAfter the data is sent, the link is disconnectedA TCP connection

HTTP level:

  • http1.0By default, short connections are used, that is, every time the browser makes a connectionhttpOperation, establish a connection once, break the connection at the end of the task, such as each static resource request is a separate connection.
  • http1.1The default is to use a long connection, which will have this lineConnection: keep-aliveIn the long connection case, when a web page is opened, the client and the server are used for transmissionhttpA TCP connectionDoes 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 ofhttp1.1There is no need to use optimization solutions (such as packaging into Sprite maps, static resources multi-domain splitting, etc.)
  • The first compression(httpHead 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:

  1. 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 numberClient random, followed by the generationSession symmetric encryption key
    • Client supportedEncryption methods, such as RSA encryption
    • Client supportedSSL/TLSProtocol version, such as TLS 1.2
  2. SeverHello

    After receiving the request from the client, the server sends the following message (in plaintext) to the client:

    • The random numberServer random, followed by the generationSession symmetric encryption key
    • To confirm theThe encryption algorithmwithThe Hash algorithm
    • confirmSSL/ TLSProtocol version. Disable encrypted communication if the browser does not support it
    • The server’sThe digital certificate(The certificate contains information such as the website address, asymmetrically encrypted public key, and certificate authority)
  3. 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 numberPremaster 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.

  4. 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.
  5. 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 (hashinghashAlgorithm, hash algorithm) :MD5, SHA1, SHA256, saltsaltIncrease 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 (forHTTPS), 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 rootCA ` ` : CACA, can be issuedCAThe certificate of
  • Root certificate: rootCASelf-signed certificates, built into the operating system and browser
The difference between HTTPS and HTTP
  1. httpThe information is transmitted in clear text, the connection is simple and stateless,httpsIs a secure encrypted transmission.
  2. httpIs directly withTCPFor data transmission,httpsIt’s through one levelSSL(OSI session layer), port former is80, which is443.
  3. httpsThe protocol handshake phase is time-consumingcaApplying for certificates or homemade certificates can increase page load time by nearly 50% and increase power consumption by 10% to 20%.
  4. httpsConnection cache is not as good ashttpHigh efficiency, increasing data overhead and power consumption, even affecting existing security measures.
  5. In August 2014, Google changed its search engine algorithm, saying, “It is better than the sameHTTPWebsite, usingHTTPSEncrypted 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

  1. Service Worker
  2. Memory Cache
  3. Disk Cache (HTTP Cache)
  4. 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:

  1. registeredService WorkerAnd then listen ininstallThe required files can be cached after the event
  2. 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
  3. If there is no cache hit, callfetchFunction retrieves data by cache priority, regardless of where the data is coming from at this pointnetWorksizeWill be displayed asService Worker

Memory Cache

  • The in-memory cache, in which almost all network requests are automatically added by the browsermemory cacheMedium, short-term storage (preload)
  • The browser TAB is closedmemory cacheThen the failure
  • Ignore HTTP headers frommemory cacheWhen obtaining cache contents, browsers ignore header configurations such as max-age=0 and no-cache
  • butCache-control:no-storeIt’s an exceptionmemory cachefailure

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:ExpiresRepresents 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-controlRepresents 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 - SinceDetermine 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 - MatchDetermine 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

  1. callService WorkerfetchIncident response
  2. To viewmemory cache
  3. To viewdisk cache
    1. 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 all200
    2. If there is a mandatory cache but it has failed, use a comparative cache and determine after comparison304or200
  4. Sends a network request and waits for a network response
  5. Store the response contentdisk cache(ifHTTPIf the header configuration can be saved)
  6. Store a reference to the response contentmemory cache(ignoringHTTPConfiguration of header information)
  7. Store the response contentService WorkerCache Storage(ifService WorkerThe script is calledcache.put())

Browser behavior

  • Open the web page, the address bar enter the address: searchdisk cacheIs there a match in. Use if available; If no network request is sent.
  • Plain refresh (F5) : Because TAB is not closed, somemory cacheIs 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 headerCache-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:

  1. (DOM) parsingHTMLContent isDOM
  2. (Recalculate Style) will beCSSconvertstyleSheetsAnd calculateDOMNode style
  3. Generate the population Tree (render Tree) and calculate the Layout information of the elements
  4. (Layer Tree) Layers the layout Tree (render Layer) to generate the Layer Tree
  5. (Paint) Generates a draw list for each layer and submits it to the composition thread
  6. (Tiles/raster) divide the layer into Tiles and convert the Tiles into bitmaps in the raster thread pool
  7. (Composite Layers) Merge the layers to form an image and save itGPUIn the memory
  8. (DrawQuad) the browser process readsGPUMemory 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.styleSheetsView the results
  • Standardized style sheets: for exampleEm - > px, red - > rgba (255,0,0,0), bold - > 700
  • Calculate eachDOMNode style: Passinheritancecascading, completes the calculation of the specific style of each element in the DOM node. throughwindow.getComputedStyleView 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 * 50Pixels, 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-indexLower 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.

Advantages and disadvantages of synthetic layer and suggestions:

  • Optimal: 1. The ratiocpuFast processing (i.eGPU hardware acceleration) 2.repaintDoes not affect other layers 3. YesDirect synthesis
  • Bad: a large number of synthetic layers will make the transfer toGPUSlow down and take upGPUAnd memory resources will also appearLayer explosion
  • Suggestion: Use animationtransformImplementation; 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 theGetComputedStyle (), getBoundingClientRect ()Or IEcurrentStyle

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 inThe transform - > top, left.visibility->display:noneEtc.
  • To animate or frequently redraw reflow nodes as separate layers, useTransform, opacity, filters, will-changeThe triggerGPUHardware-accelerated direct synthesis
  • Avoid frequent operationsDOMAnd styles, such as willdomOffline:documentFragment.display:none.clone domSetting,classClass, an update
  • Avoid the use oftableLayout as far as possibleDOMThe end of the tree changesclass
  • Avoid frequently reading properties that cause backflow/redraw
  • Avoid setting multiple inline styles,cssexpression

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

  • cssLoading does not blockDOMTree parsing (when loading asynchronouslyDOMBuild as usual)
  • But it blocks the layout tree rendering (wait while rendering)cssLoad done, because the layout tree needscssInformation)
  • Will block the backjsScript execution
  • Exception:media queryThe statementCSSIt 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 executedHTML, 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 addDefer (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)loadEvents.

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.

  1. jsThe 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.
  2. throughThe interpreter IgnitionAccording to theASTgenerateByteCode(Not directly converted to machine code because of its high memory consumption)
  3. 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 objectVO)
  • 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

  • emAs afont-sizeRepresents the font size of the parent element,emWhen used as a unit of other properties, represents its own font size.
  • remApplies 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:

  • normalAbout 1.2, depending on the font-family of the element
  • digitalLine is highDigital * the font size
  • The length of theThe line height is the length: 16px, for example
  • The percentageLine 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