Performance is a very important part of front-end development, and front-end performance optimization is an eternal topic. This article from the browser to open the page in five simple steps for a simple front-end performance optimization method comb. And combined with the project development involved in the specific introduction of three optimization methods. Lazy route loading using the packaging tool. Resource compression Gzip3. Use CDN to reduce response time.

First, use the packaging tool to load routes lazily

(1) Webpack compilation and construction process

Webpack is responsible for building and compiling and that’s Compilation.

In the WebPack Make hook, tapAsync registers a DllEntryPlugin that starts the compilation process by adding all the entry modules to the compilation build queue by calling the compiler. addEntry method.

Then call _addModuleChain in addEntry to start compiling.

In _addModuleChain, modules are generated first and then built.

After compilation is complete, the compiler. seal method is called to close and generate resources. These resources are stored in compiler. assets, compiler. chunk and will be used when writing plug-ins to Webpack.

After seal execution, the EMIT hook is called to output the file to the specified path based on the path property of the Output configuration of the Webpack Config file.

(2) Analysis of route lazy loading principle

1. Preparation

Lazy route loading can also be called lazy route component loading and is most commonly implemented through import(). After compiled and packaged by Webpack, the code of each routing component will be divided into a JS file. These JS files will not be loaded during initialization, and the corresponding JS file will be loaded only when the routing component is activated.

A simple example from the project

Use webpackChunkName to make the compiled js file name correspond to the routing component one by one. Modify the load function.

The code compression confusion is removed to make it easier to read the compiled and packaged code. It is configured in vue.config.js

2. Analysis of the index. HTML

Route component compiled and packaged corresponding JS file

  • ref=preload: Tells the browser to load the resource ahead of time.
  • rel=prefetch: Tell the browser to load the resource for me when it is free.
  • as=script: tells the browser that the resource is a script and increases the load priority.
3. Analysis the chunk – XXX. XXX. Js

Chunk-xxx.xxx. js simply pushes the following array into the window[“webpackJsonp”]. The second element of the array is an object. Each value of the object is a function expression and will not be executed.

4. Analysis of the app. XXX. Js

App.xxx. js is a self-executing function. Search window[“webpackJsonp”] to find the following code.

The firstwindow["webpackJsonp"]Assigned tojsonpArray.

Assign jsonpArray’s push method to oldJsonpFunction.

Use webpackJsonpCallback to intercept jsopArray’s push method, that is, any push method that calls window[“webpackJsonp”] will execute webpackJsonpCallback.

Shallow copy jsonpArray and assign it to jsonpArray.

For executing the chunk – XXX. Window of js [r]. “webpackJsonp” push the push method has not yet been webpackJsonpCallback function interception, so be circulation jsonpArray, Each item is passed as an argument to the webpackJsonpCallback function and called.

Assign jsonpArray’s push method to parentJsonpFunction.

5. Specific functions and functions

1) webpackJsonpCallback function

(2) checkDeferredModules function

(3) _webpack_require function

(4) webpackAsyncContext function

(5) webpack_require. E method

The __webpack_require__.e method, which is the heart of lazy loading, does three things.

  • Load the JS file corresponding to the route in JSONP mode, which can also be called chunk.
  • Set the three states of chunk loading and cacheinstalledChunksTo prevent chunk reloading.
  • Handle chunk load timeout and load error scenarios.

Three states of chunk loading

  • installedChunks[chunkId]for0, indicating that the chunk has been loaded.
  • installedChunks[chunkId]forundefined“Indicates that the chunk fails to be loaded, the loading times out, or the chunk is never loaded.
  • installedChunks[chunkId]forPromiseObject, indicating that the chunk is being loaded.

Second, resource compression Gzip

What is Gzip: Gzip is a compressed format for data, or a file format.

Gzip was originally used to compress files in UNIX systems, but has gradually become the most mainstream data compression format on the Internet. When the user visits our web site, the server will compress our web page files and transfer the compressed files to the client. For plain text files, we can compress to at least 40% of the original size, which greatly improves the transmission efficiency and the page can be loaded faster.

1. Configure the Gzip service on the Nginx server

Because our project is currently using ngxin to deploy the front end, nginx has its own HttpGzip module, so we can directly configure the HTTP configuration items in the nginx.conf file. However, since Nginx processes the request itself and then compresses it back, it consumes the corresponding server memory.

gzip on; # Minimum number of bytes allowed to compress a page, default is 0, no matter how large the page is compressed. You are advised to set the value to a value larger than 1K. If the value is smaller than 1K, the value may become larger. Set the system to obtain several units of cache for storing gzip's compressed result data stream. For example, 4 4K indicates that the memory size is four times the original data size in 4K. gzip_buffers 4 16k; Identify the protocol version of HTTP. Since some early browsers or HTTP clients may not support gzip self-extracting, the user will see garbled characters, so some judgment is necessary. Gzip_http_version 1.0; # gzip compression ratio, 1 compression ratio minimum processing speed, 9 compression ratio maximum processing speed (fast but CPU consumption). gzip_comp_level 2; The "text/ HTML "type is always compressed (whether specified or not). gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; Add gzip_vary off to the proxy server; Gzip_disable "MSIE [1-6]\."Copy the code
2. The client compresses Gzip

We should minimize the use of server memory as much as possible. After all, resources on the server side are very valuable. Here we are still using Nginx for front-end deployment. The project needs to install the webpack plug-in NPM install [email protected] -d and configure vue.config.js to register the plug-in, then run the package command. Install nginx and modify nginx.conf to start the nginx service

3. Use CDN to reduce response time

A content delivery network (CDN) is a group of Web servers distributed in multiple geographic locations. As we all know, the further the server is away from the user, the higher the latency. CDN is designed to solve this problem by deploying servers in multiple locations, bringing users closer to the server and shortening request times.

Principle of CDN

When a user visits a website without a CDN, the process looks like this:

  1. The browser needs to resolve the domain name to an IP address, so it needs to make a request to the local DNS.
  2. The local DNS sends requests to the root server, top-level domain name server, and permission server to obtain the IP address of the website server.
  3. The local DNS sends the IP address back to the browser, which makes a request to the web server IP address and gets the resource.

The process of retrieving cached content through CDN

The process diagram of request response through CDN is shown in the figure. As you can see by the picture, in the DNS domain name a new global load balancing system (GSLB), the main functions of the GSLB is based on the IP address of the user’s local DNS to judge the position of the user, users select distance closer local load balancing (SLB) system, and the SLB IP address as the results back to the local DNS. SLB is mainly responsible for judging whether the cache server in the cluster contains the resources of the user request data, if requested resource exist in the cache server, depending on the cache server in the cluster nodes, load and the number of connections of health factors such as the optimal selection of cache node, and HTTP requests will be redirected to the optimal cache node.

img

To explain the working principle of CDN more clearly, the following takes the HTTP request to “join.qq.com/video.php” initiated by the client as an example:

  1. When a user initiates an HTTP request to “join.qq.com/video.php”, the local DNS obtains the IP address of domain name “join.qq.com” through “iterative resolution”.
  2. If the local DNS cache does not contain the record of the domain name, theThe root DNSDNS query packets are sent.
  3. The root DNSIf the prefix of the domain name is “com”, the domain name is resolvedcomtheTop DNSThe IP address of
  4. Local DNS toTop DNSDNS query packets are sent.
  5. Top DNSThe prefix of the domain name is “qq.com”. Search the local record for the prefixAuthoritative DNSAnd reply to the IP address of
  6. Local DNS toAuthoritative DNSDNS query packets are sent.
  7. The authoritative DNS found a field whose NAME is “join.qq.com”CNAME record(configured by the service provider), the Value field of the record is “join.qq.cdn.com”. In addition, we also found another record whose NAME field is “join.qq.cdn.com” and whose Value field is the IP address of GSLB.
  8. The local DNS sends DNS query packets to the GSLB.
  9. GSLB according toLocal DNSThe approximate location of the user is Shenzhen, and the IP address of SLB in South China with the best overall consideration is selected to fill in the DNS reply packet as the final result of DNS query.
  10. The local DNS replies to the CLIENT’s DNS request with the IP address of the previous step as the final result.
  11. The client sends an HTTP request to the SLB based on the IP address: “join.qq.com/video.php”.
  12. SLB takes resource constraints, health, and load of each node in the cache server cluster into consideration and selects the optimal cache node to respond to the HTTP request from the client (the status code is 302, and the redirection address is the IP address of the optimal cache node).
  13. After receiving the HTTP reply from the SLB, the client redirects to the cache node.
  14. The cache node determines whether the requested resource exists or expires and directly returns the cached resource to the client. Otherwise, the cache node updates the data at the source site and replies again.

The key steps are 6 to 9. Different from the common DNS process, the service provider (source site) is required to configure its records in its authoritative DNS. The A record directly pointing to the source site is changed into A CNAME record and its corresponding A record, and the CNAME record converts the target domain name into the alias of GSLB. The A record translates the alias to the IP address of the GSLB. Through this series of operations, the power of resolving the target domain name of the source site is handed over to GSLB, so that GSLB can guide users’ requests to the nearest “cache node” according to geographical location information, which relieves the load pressure and network congestion of the source site.

The above mainly introduces the most common working mode in CDN at present. This working mode decouples domain name and target IP by using CNAME, and devolve the resolution right of target IP to GSLB, which is convenient to realize more customized functions and a more flexible way.

Reference article:

Webpack details

Front-end performance optimization

Mechanism of lazy route loading

Gzip for front-end performance optimization

Configure Nginx to use the gz-compressed files generated by WebPack directly

Half an hour to understand HTTP, HTTPS and HTTP2

24 suggestions for front-end performance optimization

CDN principle analysis \