background

As the business continues to iterate and the project grows, front-end optimization is a topic we cannot avoid in order to provide users with a better experience. An excellent website is bound to have rich functions at the same time with a relatively block of response speed, we must be more like the silky feeling when browsing the web. As a front-end engineer, project optimization mainly focuses on the following points: white screen time, first screen time, full page time, DNS time, and CPU usage. As far as our current project is about Angular development, the first screen load time is 9.2 seconds, which greatly reduces the user experience. Through this optimization, the first screen load is reduced to 3.6 seconds, and the optimization process will be explained step by step.

PageSpeed Insights locates the problem

In fact, I had the idea of optimizing the home page of the project long before, because the concept of front-end optimization is relatively huge and covers a wide range, and I often have no way to start with the project. I also read and borrowed a lot of good articles before optimization, and finally found a very useful tool -PageSpeed Insights for Chrome. This is a Chrome plugin that can be used to locate performance problems on web pages. Once installed, add it to DevTools and start having fun finding problems.As you can see from the example above, PageSpeed Insights will classify and list the problems existing in the web page to be optimized, and each class can be located to specific files, so that the original very abstract front-end optimization is visualized in front of our eyes. The direction of optimization is mainly divided into code compression, browser caching, static resource compression. Once the direction is clear, you can start to reform around the problem.

Front-end optimization generally relies on the phrase, reduce the number of requested files and reduce the size of requested files.

Code compression

Combined with the thought of front-end engineering, I will divide the code compression into two categories, one is the compression of files when the project is built using packaging tools, such as the configuration of Webpack various compression Plugin, the other is the compression configuration of the front-end server transmission response, such as Nginx Gzip.

Webpack configuration

Because Angular-CLI integrates Webpack internally and rewraps it, optimizing or changing the Webpack configuration in Angular 6.0+ projects goes through Angular-Builders, where we need to install the package separately. Of course, if the project is packaged directly with Webpack, you can skip this step.

npm install @angular-builders/custom-webpack --save-dev
npm install @angular-devkit/build-angular --save-dev
Copy the code

There is no need to install webPack and webpack-dev-server separately because they are dependencies of @angular-devkit/ build-Angular. Install @angular-devkit/ build-Angular automatically installs WebPack and webpack-dev-server.

To change the angular.json file configuration after installation, add the webpack configuration we will add later to the run (serve) and build (build) commands. The key configuration is as follows:

"architect": {
        ......
        "build": {
            "builder": "@angular-builders/custom-webpack:browser",
            "options": {
                "customWebpackConfig": {
                    "path": "./webpack.config.js"
                }
            }
        },
        "serve": {
            "builder": "@angular-builders/custom-webpack:dev-server",
            "options": {
                "customWebpackConfig": {
                    "path": "./webpack.config.js"
                }
            }
        }
    }
Copy the code

Next, you need to create a configuration file in the root directory, which I’ll call webpack.config.js. The links to Angular and custom Webpack configurations are in place at this point, and we can now write the required Webpack configuration into the new file. Javascript compression: UglifyJsPlugin, Html compression HtmlWebpackPlugin, extract common resources: CommonsChunkPlugin, extract Css and compress: ExtractTextPlugin.

Configure Nginx compression

Since all of our front-end projects are deployed through Nginx, we also need to enable Gzip transport compression on Nginx, which reduces the size of the packaged files transferred to about a quarter of their original size.

gzip on;
gzip_types text/plain application/javascriptapplication/x-javascripttext/css application/xml text/javascriptapplication/x-httpd-php application/vnd.ms-fontobject font/ttf font/opentype font/x-woff image/svg+xml;
Copy the code

Nginx: Content-encoding: gzip: Nginx: Content-encoding: gzip: Nginx: Content-Encoding: gzip: Nginx: Content-Encoding: gzip: Nginx: Content-Encoding: gzip: Nginx

Static resource compression

Use Sprite

The function of Sprite image is to reduce the number of requests, and the volume of multiple images combined will be less than the total volume of multiple images. This is also a common image compression scheme, and a Sprite image generation tool is recommendedsprite-generator

Use WebP format images

WebP is an image format developed by Google team to speed up the image loading speed. Its advantages are reflected in its better image data compression algorithm, which can bring smaller image volume, and has the image quality of naked eye recognition without difference, as well as lossless and lossy compression mode, Alpha transparency and animation features. The conversion results on JPEG and PNG are excellent, stable and uniform. Also recommended is a tool to generate WebP formatPat cloud WebP again

Load using CDN

Content delivery network (CNET) is a computer network system connected through the Internet that delivers music, pictures, videos, applications and other files to users faster and more reliably using the server closest to each user, providing high performance, scalability and low cost delivery of web content to users. By introducing the external resource package referenced in the project through CDN, it can reduce the volume of project package file and improve the speed of resource request.

Page rendering performance optimization

Reduce rearrangement and redraw

The following three conditions can cause the page to be re-rendered

  • Modify the DOM
  • Modify the style
  • User events

Rerendering is rearranging and redrawing, the former called reflow and the latter called repaint. Rearranging and redrawing can affect page performance and user experience, so you need to minimize the frequency of rearranging and redrawing. Pay attention to the following aspects.

  • Multiple DOM read operations should be written together. Do not add write operations to consecutive READ operations.
  • If the style is rearranged, cache the style as much as possible.
  • Don’t change styles alone. It’s better to change them collectively through Class.
  • Use the offline DOM as much as possible to change styles before writing objects.
  • So let’s set the element to zerodisplay: noneAnd then perform operations on the node.
  • The position ofabsolutefixedThe element rearrangement overhead is compared under, because the influence of other elements is not considered.
  • Nodes that display: None will not be added to the Render Tree, and visibility:hidden will, so if a node is not initially displayed, setting display: None is preferable.

Avoid CSS and JS blocking

When talking about resource blocking, it’s important to remember that modern browsers always load resources in parallel. For example, when an HTML parser is blocked by a script, the parser stops building the DOM but still recognizes the resources behind the script and preloads them. By default, CSS is treated as a resource that blocks rendering, which means that the browser will not render any processed content until CSSOM is built and Javascript can read and modify not only DOM properties, but CSSOM properties as well. Browsers delay javascript execution and Render Tree builds. When the browser encounters a script tag, DOM build is paused until the script completes execution. Javascript can query and modify the DOM with CSSOM when CSSOM is built, javascript execution will be paused until CSSOM is ready. Therefore, the position of the script tag is important. In practice, you can follow the following two principles

  • CSS resources are better than JS resources
  • JS should affect DOM construction as little as possible

There are two ways to change JS blocking: defer and async defer. Script loading does not block HTML parsing, and js is executed after DOM generation and script loading is complete. Async property indicates that the JS introduced by asynchronous execution will not block HTML parsing when loaded, but will still block the load event when executed immediately after loading.

conclusion

Front-end optimization is a long-term project, and the above is only part of the content and direction of optimization. In the future, we will keep paying attention to front-end optimization and improve project performance through a more comprehensive dimension.