31

background

Everyone who has done front-end development knows that there are a lot of front-end work content, such as the use of HTML, CSS, Javascript, Image, Flash and other content. In order to better improve the performance of the application, we need to optimize the content of various resources in different aspects.

For users, optimization can speed up the response speed of the application, load more quickly, and bring a better user experience.
For service providers, front-end optimization can reduce the number of page requests, the bandwidth occupied by broadband, and effectively save resources.

There are many front-end optimization content, which can be roughly divided into two categories according to the granularity level: page optimization level and code level optimization.
Page optimization is mainly for page loading, including: the number of HTTP requests, the non-blocking loading of scripts, and the location optimization of inline scripts. Code optimization includes: DOM operation optimization in Javascript, CSS selector optimization, image optimization, and HTML structure optimization.

Code level optimization pays more attention to data requests, and one of the most important ones is to reduce the number of HTTP requests. A complete HTTP request needs to go through a series of processes such as route lookup, TCP handshake, sending request, server response, and browser reception. For small files, the actual download time accounts for a very low proportion of the entire request time, so it is necessary to merge small files into large files for transmission.

1.webp

(The picture comes from the Internet)

Page level: Improve page loading speed

Loading optimization is to solve the problem that page content loading speed is limited by network bandwidth, which is too time-consuming. The main methods are:
Project packaging optimization
Webpack is a front-end resource loading/packaging tool. It will perform static analysis based on the dependencies of the modules, and then generate corresponding static resources from these modules according to the specified rules. Usually we use Webpack to convert a variety of static resources js, css, and less into a static file, reducing page requests.
The core concepts are:
Output: Tell webpack where to output the bundles it creates and how to name these files. The default value is ./dist.
Module: Webpack will recursively find all dependent modules from the configured Entry.
Chunk: A Chunk is composed of multiple modules and is used for code merging and splitting.
Loader: Loader can convert all types of files into effective modules that webpack can handle, and then you can use webpack's packaging capabilities to process them.
Plugin: Used to convert certain types of modules, and plug-ins can be used to perform a wider range of tasks.

CSS Sprite

CSS Sprite is CSS Sprite, and some people call it CSS sprite. It is a CSS image merging technology. The method is to merge small icons and background images into one image, and then use the background positioning of CSS to display the part of the image that needs to be displayed. .

The basic principle of Sprite Map is to integrate the pictures we use from the Internet into the same picture, which can reduce the number of HTTP requests for the website. This image is rendered using CSS background and background-position properties,
This means that our tags have become more complex, and images are defined in CSS instead of <img> tags.

There are two obvious advantages of using Sprite:

  1. Reduce the number of requests for web page image content to the server
    Sprite can merge most background pictures and small icons, which is convenient for us to use in any position. Requests from different locations will only call the same image, which greatly reduces the number of page requests to the server and reduces the pressure on the server; this can also increase the loading speed of the page and save server traffic.
  2. Improve page loading speed
    The size of the spliced pictures of Sprite is significantly smaller than the size before all pictures are merged.
    From these two aspects, the front-end request speed can be obviously optimized.
    After HTTP2, there is no longer any need to consider reducing the number of requests, so Sprite Graph now makes little sense in optimizing performance on the front-end page. Now it is more recommended to use font icons, the files are small and vector icons
    CDN acceleration
    The full name of CDN is Content Delivery Network, that is, content delivery network. Its purpose is to add a new CACHE (cache) layer to the existing Internet, and publish the content of the website to the node closest to the user's network "edge", so that users can obtain the content they need nearby, and improve users. The response speed of visiting the website. Technically, it solves the reasons such as small network bandwidth, large user visits, uneven distribution of outlets, etc., and improves the response speed of users visiting the website.

Cache layer technology can be used to eliminate node device congestion caused by peak data access. The Cache server has a caching function. Repeated access to most of the webpage objects does not require retransmission of the file from the original website, but only needs to send a copy through simple authentication. The location of the cache server is usually not near the user end, so the response speed of the local area network can be obtained, and the wide-area broadband consumption can be effectively reduced.
It is very effective for improving response speed, saving bandwidth, and effectively reducing the load of the source server.

In summary, the optimization effect of CDN on the network is mainly reflected in the following aspects:

  • Solve the "first mile" problem on the server side
  • Alleviate or even eliminate the impact of interconnection bottlenecks between different operators
  • Reduce the pressure on export bandwidth in various provinces
  • Relieved the pressure on the backbone network
  • Optimized the distribution of online hot content

gzip compression

Gzip is the abbreviation of GNUzip, a GNU free software file compression program, which can basically compress 50% of the text file size in use. Before talking about Gzip, we first introduce a concept, HTTP compression. HTTP compression is a method that is built into web pages and web clients to improve transmission speed and bandwidth utilization. In the case of HTTP compression, the HTTP data is compressed before it is sent from the server: compatible browsers will announce which methods are supported to the server before downloading the required format; browsers that do not support the compression method will download Compressed data.
HTTP compression is the process of re-encoding HTTP content for the purpose of reducing the size.
Gzip is a classic example of HTTP compression.

Reducing the file size brings two obvious benefits:

  1. Reduce storage space
  2. Can reduce the transmission time when transmitting through the network

The principle behind Gzip compression is to find some repetitive strings in a text file and replace them temporarily, thereby making the entire file smaller. It is precisely because of this principle that the higher the repetition rate of the code in the file, the higher the efficiency of Gzip compression, and the greater the benefit of using Gzip. vice versa.

Project packaging optimization

2.jpg

(The picture comes from the Internet)

Webpack is a front-end resource loading/packaging tool. It will perform static analysis based on the dependencies of the modules, and then generate corresponding static resources from these modules according to the specified rules. Usually we use Webpack to convert a variety of static resources js, css, and less into a static file, reducing page requests.
The core concepts are:
Output: Tell webpack where to output the bundles it creates and how to name these files. The default value is ./dist.
Module: Webpack will recursively find all dependent modules from the configured Entry.
Chunk: A Chunk is composed of multiple modules and is used for code merging and splitting.
Loader: Loader can convert all types of files into effective modules that webpack can handle, and then you can use webpack's packaging capabilities to process them.
Plugin: Used to convert certain types of modules, and plug-ins can be used to perform a wider range of tasks.

CSS Sprite

3.webp

(The picture comes from the Internet)

CSS Sprite is CSS Sprite, and some people call it CSS sprite. It is a CSS image merging technology. The method is to merge small icons and background images into one image, and then use the background positioning of CSS to display the part of the image that needs to be displayed. .

The basic principle of Sprite Map is to integrate the pictures we use from the Internet into the same picture, which can reduce the number of HTTP requests for the website. This image is rendered using CSS background and background-position properties,
This means that our tags have become more complex, and images are defined in CSS instead of <img> tags.

There are two obvious advantages of using Sprite:

  1. Reduce the number of requests for web page image content to the server
    Sprite can merge most background pictures and small icons, which is convenient for us to use in any position. Requests from different locations will only call the same image, which greatly reduces the number of page requests to the server and reduces the pressure on the server; this can also increase the loading speed of the page and save server traffic.
  2. Improve page loading speed
    The size of the spliced pictures of Sprite is significantly smaller than the size before all pictures are merged.
    From these two aspects, the front-end request speed can be obviously optimized.
    After HTTP2, there is no longer any need to consider reducing the number of requests, so Sprite Graph now makes little sense in optimizing performance on the front-end page. Now it is more recommended to use font icons, the files are small and vector icons

CDN acceleration

4.jpg

(The picture comes from the Internet)

The full name of CDN is Content Delivery Network, that is, content delivery network. Its purpose is to add a new CACHE (cache) layer to the existing Internet, and publish the content of the website to the node closest to the user's network "edge", so that users can obtain the content they need nearby, and improve users. The response speed of visiting the website. Technically, it solves the reasons such as small network bandwidth, large user visits, uneven distribution of outlets, etc., and improves the response speed of users visiting the website.

Cache layer technology can be used to eliminate node device congestion caused by peak data access. The Cache server has a caching function. Repeated access to most of the webpage objects does not require retransmission of the file from the original website, but only needs to send a copy through simple authentication. The location of the cache server is usually not near the user end, so the response speed of the local area network can be obtained, and the wide-area broadband consumption can be effectively reduced.
It is very effective for improving response speed, saving bandwidth, and effectively reducing the load of the source server.

In summary, the optimization effect of CDN on the network is mainly reflected in the following aspects:

  • Solve the "first mile" problem on the server side
  • Alleviate or even eliminate the impact of interconnection bottlenecks between different operators
  • Reduce the pressure on export bandwidth in various provinces
  • Relieved the pressure on the backbone network
  • Optimized the distribution of online hot content

gzip compression

5.jpg

(The picture comes from the Internet)

Gzip is the abbreviation of GNUzip, a GNU free software file compression program, which can basically compress 50% of the text file size in use. Before talking about Gzip, we first introduce a concept, HTTP compression. HTTP compression is a method that is built into web pages and web clients to improve transmission speed and bandwidth utilization. In the case of HTTP compression, the HTTP data is compressed before it is sent from the server: compatible browsers will announce which methods are supported to the server before downloading the required format; browsers that do not support the compression method will download Compressed data.
HTTP compression is the process of re-encoding HTTP content for the purpose of reducing the size.
Gzip is a classic example of HTTP compression.

Reducing the file size brings two obvious benefits:

  1. Reduce storage space
  2. Can reduce the transmission time when transmitting through the network

The principle behind Gzip compression is to find some repetitive strings in a text file and replace them temporarily, thereby making the entire file smaller. It is precisely because of this principle that the higher the repetition rate of the code in the file, the higher the efficiency of Gzip compression, and the greater the benefit of using Gzip. vice versa.

Code level: reduce the number of data requests

Earlier we listed the optimization methods during the initial loading of the page, but in some scenarios this is not enough, because there are often scenarios where the page is displayed and used, and the service is frequently requested to update the information.

For example, when developing an Excel-like online collaboration system, because cell services are independent of each other, full-screen refresh cannot meet the demand. We can only get the value of each cell from the server regularly, and display it on the page after detecting the change. And each cell separately calls the api to obtain the content, which will generate a large number of network requests. On the one hand, a large number of requests slows down the loading speed, and the page freezes.

In this scenario, WebSocket is a good choice. It maintains synchronization with the server through a long link, and the server actively pushes updates to the client, reducing network overhead. However, WebSocket also has its own shortcomings and high development costs. Both the client and the server need to consider issues such as disconnection and reconnection, frequent push, and resource occupation. Therefore, we also need to optimize to minimize the frequency of requests.

Optimization ideas

How to reduce the number of data requests? We can optimize the logic by requesting the queue.

7.png

(Optimize web requests through request queue)

After optimization, the logic of obtaining data from an Excel-like online collaborative system has become as follows:

  • When a cell sends a request, the request first adds an ID, and caches the callback method through the ID, and then enters the request queue. The queue manager sends a request packet regularly or according to the number of requests in the queue.
  • The server receives the request packet and processes it in batches, and encapsulates the new return packet after processing
  • After receiving the returned package, the front end calls the corresponding callback method to execute according to the unique ID of the request to complete the cell request
    The advantages of using this method for optimization are obvious:
  • The implementation is simple, the code changes little, the original ajax request can be changed to a queue call, and the callbak after the request does not need to be modified. The server simply adds a new interface to split the request.
  • Set the request frequency or the amount of data in a request according to the actual scenario, taking into account the update frequency and the corresponding number of times.

Applications

The following code is the implementation of GETNUMBERFROMSERVER. This function is responsible for calling the server's getData interface, passing parameters, obtaining the displayed content and displaying it in the cell. In order to ensure the user experience of updating cells asynchronously, this function is derived from the asynchronous function of SpreadJS

1.        var GetNumberFromServer = function () {
2.        };
3.        GetNumberFromServer.prototype = new GC.Spread.CalcEngine.Functions.AsyncFunction("GETNUMBERFROMSERVER", 1, 2);
4.        GetNumberFromServer.prototype.evaluate = function (context, arg1, arg2) {
5.        fetch("/spread/getData?data="+arg1)
6.        .then(function(response) {
7.            return response.text();
8.        })
9.        .then(function(text) {
10.            context.setAsyncResult(text);
11.        });
12.        };
13.        GC.Spread.CalcEngine.Functions.defineGlobalCustomFunction("GETNUMBERFROMSERVER", new GetNumberFromServer());
14.    

In order to reduce requests, we first need to use a cache object to store the requested data, and call the interface regularly for processing.

1.    let callStack = {}; //收集请求数据
2.    let callingStack = {}; //缓存正在请求中的数据信息
3.    let callStackCount = 0; //请求数量,当作请求ID,用于区分请求内容
4.    let timingId = 0; //用于判断当前是否有定时器等待请求中

Then, we define a new queued request method instead of calling the API interface directly in the function.

1.    
2.    // data 请求数据
3.    // context 异步函数context, 网络请求结束后回调时使用
4.    // callback 回调函数
5.    function stackCall(data, context, callback){
6.        let id = callStackCount++;
7.        callStack[id] = {};
8.        callStack[id].data = data;
9.        callStack[id].context = context;
10.        callStack[id].callback = callback;
11.    
12.        if(timingId === 0){ // 同时只有一个定时器
13.            timingId = setTimeout(function(){
14.                callingStack = callStack;
15.                callStack = {};
16.    
17.                let newData = "" //合并请求数据,根据实际业务情况整理
18.                for(let cId in callingStack){
19.                    newData += (cId + "," + callingStack[cId].data + ";");
20.                }
21.    
22.                // 发送请求,这里模拟数据,发送什么返回什么
23.                fetch("/spread/getData?data=" + newData)
24.                      .then(function(response) {
25.                        return response.text();
26.                      })
27.                      .then(function(text) {
28.                        let resData = newData.split(";");
29.                        let spread = designer.getWorkbook();
30.                        spread.suspendPaint(); //暂定页面绘制
31.    
32.                        //解析返回的数据
33.                        for(let resId in resData){
34.                            if(resData[resId]){
35.                                let ress = resData[resId].split(",");
36.                                // 根据Id,获取函数的context,调用callback回调
37.                                callingStack[ress[0]].callback.call(null, callingStack[ress[0]].context, ress[1])
38.                            }
39.                        }
40.                        spread.resumePaint(); //重启统一绘制
41.                    timingId = 0;
42.                });
43.            }, 1000)
44.        }
45.    }

Finally, update the implementation of the asynchronous function, call the stackCall stack function in the function, and execute the setAsyncResult method in the callback callback after the batch call is successful, and finally realize the business logic.

1.    GetNumberFromServer.prototype.evaluate = function (context, arg1, arg2) {
2.        stackCall(arg1, context, function(context, text){
3.            context.setAsyncResult(text);
4.        })
5.        };


After this optimization, when there are a large number of asynchronous requests on the page, these requests will be put in the queue, processed regularly and refreshed once.

In addition, we can also use SpreadJS's doNotRecalculateAfterLoad import option, which does not calculate at the first load, but uses the original value in json; and calcOnDemand enables on-demand calculation. Further optimize the speed and experience of page initialization.


1.    json.calcOnDemand = true;
2.    spread.fromJSON(json, { doNotRecalculateAfterLoad: true });

to sum up

This article classifies and introduces several front-end performance optimization methods. These best practices cover page loading and data request links. In the second half of the article, we introduced in detail the implementation of "data request queuing" through an example of online collaborative editing like Excel. We hope it will be helpful to your front-end development.

Questionnaire

In 2020, a sudden black swan incident has made "online office" a major success. DingTalk, Enterprise WeChat, Feishu and other online office software continue to emerge, completely subverting the traditional business management model and greatly improving the company. Office efficiency.

In 2021, the popularity of “online office” has not decayed with the full resumption of work and production. On the contrary, under the digital wave, the online office market has great potential. The old players in the track continue to increase their weight, and the new players are also starting Run into the arena.

For developers, how can they develop an online document system that adapts to future office scenarios, take advantage of the “online office” trend, and break the “BATHZ” battle?

In order to answer this question, Grape City intends to hold a seminar on "Application and Future Development of Form Products in Collaborative Documents". Now we collect your thoughts on this event: https://www.wenjuan. com/s/nmANzan/


葡萄城技术团队
2.7k 声望28.5k 粉丝

葡萄城创建于1980年,是专业的软件开发技术和低代码平台提供商。以“赋能开发者”为使命,葡萄城致力于通过各类软件开发工具和服务,创新开发模式,提升开发效率,推动软件产业发展,为“数字中国”建设提速。