Thoroughly master “Front-end Performance Optimization” based on HTTP Network layer

Product performance optimization scheme

  • HTTP network layer optimization
  • The code compilation layer optimizes Webpack
  • Code run layer optimized HTML/CSS + javascript + vue + React
  • Security optimization XSS + CSRF
  • Data burying point and performance monitoring

CRP (Critical [ˈkrɪtɪkl] Rendering [ˈrendərɪŋ] Path

Question: What happens between entering the URL and seeing the page

The first step is URL parsing
  • Transfer protocol: HTTP/HTTPS (SSL)/FTP (file upload)…
  • Domain name: top-level domain name, level 1 domain name, level 2 domain name
    • buyTop-level domain names
    • The same primary domain and different subdomains belong to cross-domains
  • Port number: 0 to 65535 HTTP:80 HTTPS:443 FTP: 21 The default port number is for browser processing.
    • Question mark parameter: can pass some information to the server “GET” series; Also can realize the information communication between two pages; SPA single page, realize the communication between components
  • HASH HASH value: Anchor location: HASH Route:…

Encoding the encoding of the particular content in the URL

EncodeURI decodeURI is weak to compile (usually compile a whole HTTP section)

EncodeURIComponent decodeURIComponent strong compilation ability (general compilation of part of the Chinese characters in HTTP)

Escape unescape compiler between clients let’s say I want to compile Chinese characters to save cookies

Step 2: Cache check
  • Look for memory first and then look for hard disk

  • F5 Common refresh: Memory => Hard disk

  • Reopen the page: hard disk

  • CTRL+F5 Force refresh: Send requests directly to the service without checking any cache

    Strong @ 1 cache(Server Settings)
    • First check whether there is a local cache, yes, and no expiration, directly local fetch, and then render [HTTP status code 200]
    • If not, the request is re-sent to the server, the latest result is pulled, and the result is cached while rendering
    • .

    Advantages: @1 performance optimization is an important means to ensure that the second and subsequent re-access to the product is fast…

    Cons: @1 HTTP can’t be cached

    @2 As long as HTTP does not make strong cache, we can ensure that its resources are updated in time. After requesting resources, set timestamp or file name to generate HASH name according to the content…

    The server sets the set strong Cache: Each time the latest resource file is pulled from the server, the client automatically caches the information, including its expiration date…., in the request header with Expires/cache-control Access to these resources later depends on whether they are locally available and expire.

    • Expires: cache expiration time, used to specify when a resource Expires (HTTP/1.0)
    • Cache-control: cache-control: max-age=2592000 Within 2592000 seconds (30 days) after the first access to the resource, send the request again to read the information in the Cache (HTTP/1.1).
    • Cache-control takes precedence over Expires when both are present

Negotiate the cache last-Modified/ETag304 Negotiation cache is validated only after strong cache is invalid
  • theLast-Modified / ETagstoredLast-ModifiedIndicates the time when the current resource file was last modified on the serverETagEach change generates a tag
  • Request this page again, strong cache does not take effect, start negotiating cache
    • Send a request to the server and take it with youif-Modifyed-Since:Last-Modified if-None-Match:ETagPass to the server; The server will compare the passed time/flag with the last modified time/flag of the server’s natural resource file. If it is the same, the file has not been updated.Go straight back to 304Last-modified /ETag/last-modified /ETag/last-modified /ETag

Negotiation caching can be used for HTML file resources

Data cache

Step 3: DNS resolution
  • On the DNS server, find the extranet IP based on the domain name. Later we can find the server based on the extranet IP of the server

  • DNS prefetch (locally obtained)

    <meta http-equiv="x-dns-prefetch-control" content="on">
    <link rel="dns-prefetch" href="//static.360buyimg.com"/>
    <link rel="dns-prefetch" href="//misc.360buyimg.com"/>
    <link rel="dns-prefetch" href="/ / img10.360buyimg.com"/>
    <link rel="dns-prefetch" href="//d.3.cn"/>
    <link rel="dns-prefetch" href="//d.jd.com"/>
    Copy the code
  • Large projects tend to split servers

    Advantages of server split

    • Rational utilization of resources

    • Increased ability to withstand pressure

    • Improve HHTP concurrency

    • .

  • You can modify the local HOST to resolve cross-domain

    • HOST

Step 4: TCP three-way handshake

Step 5: Data transfer
Step 6: TCP wave four times

Connection: keep-alive indicates a long Connection

Step 7: Render the page
Summary steps:
+ Handle HTML tags, build DOM trees + Handle CSS tags, build CSSOM trees + Fuse DOM and CSSOM trees into render trees + Calculate their exact location and size in the device viewport according to the generated render trees. The stage of this calculation is reflow => Layout or reflow + get the absolute pixels of the nodes based on the render tree and the geometry information obtained by reflow => paintingCopy the code

The main processes and responsibilities of the browser

What is CRP (Critical Rendering Path)? How to optimize

The key render path is the series of steps that the browser goes through to convert HTML, CSS, and JavaScript into pixel content rendered on the screen. This is the browser rendering process we talked about above.

We want to optimize from the following three latitudes

  • Number of critical resources: Number of requested resources
  • Critical path length: number of round trips or total time required to obtain all critical resources
  • Key bytes: The total number of bytes required to achieve the first rendering of a web page, equal to the size of all key resource transfer files combined.

Optimization of the DOM

  • Remove unnecessary code and comments including Spaces to minimize the file as much as possible.
  • You can use GZIP to compress files
  • HTTP cache file

CSSOM

  • Reduce the number of key CSS elements
  • Reduce CSS nesting
  • style/link/Reduce @ import

js

  • async

  • defer

  • preload

  • DNS pretreatment

Talk about backflow and redraw of browsers
  • Backflow will certainly cause repainting, and repainting will not necessarily cause backflow.
  • Manipulating the DOM can cause backflow in the browser (such as DOM location changes), which is why DOM manipulation is inefficient

What operations can cause backflow

  • The first rendering of the page
  • The browser window size changed. Procedure
  • The size or position of the element changes. The content of the element changes (the number of words or the size of images, etc.).
  • The element font size changed
  • Add or remove visible DOM elements

Redraw (Repaint)

  • When a change in the style of an element in a page does not affect its position in the document flow (e.g., color, background-color, visibility, etc.), the browser assigns the new style to the element and redraws it, a process called redraw.

How to reduce backflow and redraw

  • Instead of manipulating the DOM in the traditional way, vUE/React started to influence views

  • Reading and writing separation

    The browser's queue rendering mechanism

    • Gets style refresh browser render queue
  • Document fragments

    let box = document.querySelector('#box'),
        frag = document.createDocumentFragment();
    for (let i = 0; i < 10; i++) {
        let span = document.createElement('span');
        span.innerHTML = i + 1;
        frag.appendChild(span);
    }
    box.appendChild(frag);
    
    / * - * /
    let box = document.querySelector('#box'),
        str = ` `;
    for (let i = 0; i < 10; i++) {
        str += `<span>${i+1}</span>`;
    }
    box.innerHTML = str;
    Copy the code
  • Css3 Hardware acceleration (GPU acceleration)

    • transform \ opacity \ filters

Performance Optimization Summary

/* * 1. Use cache * + to implement strong cache and negotiated cache for static resource files. * + for not updated frequently USES the local storage interface data for data cache (extension: cookies/localStorage vuex | redux difference?) * 2.DNS optimization * + split server deployment to increase HTTP concurrency (resulting in slow DNS resolution) * + DNS Prefetch * 3.TCP three-way handshake and four-way wave * + Connection:keep-alive * 4. Data transfer * + Reduce the size of data transfer * + Content or data compression (webpack, etc.) * + Server side must be enabled GZIP compression (generally about 60% compression) * + batch requests for large quantities of data (e.g. Pull down refresh or paging to ensure the first load request data is less) * + reduce the number of HTTP requests * + resource file merge processing * + font icon * + Sprite image CSS-sprit * + BASE64 * +...... * 5.CDN server "geographical distribution" * 6. Using HTTP2.0 * ============== * Network optimization is the focus of front-end performance optimization, because most of the consumption occurs in the network layer, especially the first page load, "Reduce the effect and time of white screen" * + LOADDING User-friendly experience * + Skeleton screen: Client skeleton screen + Server skeleton screen * + picture lazy loading * +.... * /
Copy the code

HTTP1.0 VS HTTP1.1 VS HTTP2.0

Some differences between HTTP1.0 and HTTP1.1
  • Cache handlingHTTP1.0 uses last-Modified expires as a buffer control. HTTP1.1 introduces more cache-control policies: ETag, cache-control…
  • Bandwidth optimization and network connection usageHTTP1.1 supports Partial Content 206
  • Management of error notificationsAdd 24 error status response codes in HTTP1.1. For example, 409 (Conflict) indicates that the requested resource is in Conflict with the current state of the resource. 410 (Gone) Indicates that a resource on the server is permanently deleted…
  • The Host header processingHTTP1.0 assumes that each server is bound to a unique IP address, so the URL in the request message does not pass the hostname. However, with the development of virtual hosting technology, there can be multiple virtual hosts (multi-homed Web Servers) on a physical server, and they share the same IP address. HTTP1.1 Request and response messages should support the Host header field, and an error will be reported if there is no Host header field in the Request message (400 Bad Request)
  • A long connectionIn HTTP1.1, Connection: keep-alive is enabled by default, to compensate for the fact that HTTP1.0 requires a Connection to be created on every request
New features of HTTP2.0 compared to HTTP1.x
  • New Binary Format, HTTP1. X analysis is based on the text, based on the analytical natural defects of text format of the agreement, the text has a diversity of forms of expression, to achieve robustness consideration of scene will be many, binary, on the other hand, only the combination of 0 s and 1 s, based on this consideration HTTP2.0 protocol parsing decided to adopt the binary format, realize the convenient and robust
  • The header compressionHttp1.x uses encoder to reduce the size of the header to be transferred. The two parties cache a table of header fields to avoid the transmission of duplicate headers. It also reduces the size of the transfer required
  • Server pushFor example, my web page has a request for sytl. CSS. When the client receives the sytl. CSS data, the server will push the sytl. js file to the client. When the client tries to obtain sytl. js again, it can directly obtain it from the cache without sending the request again
  • MultiPlexing
- HTTP/1.0Each time a request is responded, a TCP connection is established and closed - HTTP/1.1"Long connection" a number of requests queue serialized single thread processing, the subsequent request waiting for the return of the previous request to get the opportunity to execute, once a request timeout, etc., the subsequent request can only be blocked, there is no way, that is, people often say the thread head blocking; - HTTP/2.0"Multiplexing" multiple requests can be executed in parallel on one connection at the same time. A request task is time-consuming and does not affect the normal execution of other connections.Copy the code

Talk more about GET/HEAD/DELETE/OPTIONS

GET

GET, arguably the most common, is essentially sending a request to retrieve a resource on the server. Resources are returned to the client through a set of HTTP headers and render data (such as HTML text, or images or videos). Render data is never included in a GET request.

HEAD

HEAD and GET are essentially the same, except that HEAD contains no render data, only HTTP headers. Some people may think that this method is useless, but it is not. Imagine a business situation: To determine whether a resource exists, we usually use GET, but HEAD makes more sense.

app.head('/head', ((req,res) = > {
    res.type('application/json').send('ok')}))Copy the code

Usage scenarios
  • You can use HEAD to check if a file exists. There is no need to use GET to fetch the entire file.
  • Check to see if the file has the latest version. You can also use HEAD, where the server will return the modification time of the file in the response header.
Note:

Get requests in Express can also accept head requests

OPTIONS

This is the browser’s way of dealing with complex cross-domain requests. Before actually sending the request, it sends an OPTIONS request to see if the server is responding correctly and if the status is wrong it will stop the second real request

What is a complex request

// Set cross-domain
app.use((req, res, next) = > {
    res.header('Access-Control-Allow-Origin'."http://127.0.0.1:5500");
    // The access-Control-allow-headers header is used in a Preflight request
    res.header('Access-Control-Allow-Headers'."Origin, X-Requested-With, Content-Type, Accept, Authorization");
    if(req.method ==='OPTIONS'){
        res.send('ok')
    } 
    next();
})
Copy the code

DELETE

Request server to remove the resource identified by request-URL (semantic)

This thing just tells you I’m deleting files nothing special

app.delete('/delete'.function (req, res) {
    res.send('DELETE request to homepage')})Copy the code

PUT

The difference between PUT and POST is that the PUT method is idempotent: calling it once is equivalent to calling it multiple times in a row (that is, without side effects), while calling it multiple times in a row can have side effects, such as repeating an order multiple times.

@1 If it is an update, no new data will be generated, the new data will overwrite the old data, put, if it is a create, new data will be generated, post.

@2 Operations that modify a class, such as changing a user name or password, are idempotent, so they are PUT requests. Increment operations are not idempotent.

patch

Local update

Conclusion:

Even if I just use POST, or even Create my own HTTP Method, I can still do all the work. The meaning of the existence of standards is to provide you with a set of default general rules, if we follow, then communication, system docking, will save a lot of unnecessary costs, a large part of the significance of these standards is to reduce the cost of maximum effort.