This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

preface

As our front-end engineering becomes larger and more complex, front-end optimization becomes more and more important.

  • The browser enters the URL to the page display, what happens specifically, what can be done to optimize the front end
  • DNS recursive query resolution — DNS optimized prefetch;
  • TCP three handshakes, four waves — http1.0/1.1/2.0 difference, HTTP/S difference;
  • HTTP cache — 304 with CDN;
  • Webpack – resource packaging strategy
  • Browser rendering mechanism – importance of CSS, JS order, @import loss, buffering, throttling, rearranging, redrawing, GPU acceleration, etc.
  • How to optimize JS main thread — Web worker, task sharding
  • .

There’s really a lot of front-end performance optimization to do, and here are some of the more common ones that you can check for yourself.

DNS recursive query resolution

Recursive resolution (or “recursive query”, which means the same thing) is the most common and default resolution method. In this resolution mode, if the Local DNS server configured on the client (also called Local DNS, which can be the default Local DNS provided by the carrier or the DNS configured by the client) fails to resolve the DNS, the Local DNS server performs all subsequent queries instead of the DNS client. Until the local nameserver gets the correct resolution from the authoritative nameserver, the local nameserver tells the DNS client the result of the query.

Of course, in the actual situation, we may have a web page resources from different domain names. In this case, pre-resolution is used to perform pre-query on the resources that need DNS query in idle time to improve the loading speed.

<html>
  <head>
    <link rel="dns-prefetch" href="https://fonts.gstatic.com/">
    <! -- and all other head elements -->
  </head>
  <body>
    <! -- your page content -->
  </body>
</html>
Copy the code

TCP shakes hands three times and waves four times

Three-way Handshake is when a TCP connection is established with a total of Three packets sent by the client and server.

The purpose of the three-way handshake is to connect to the specified port of the server, establish a TCP connection, synchronize the serial number and acknowledgement number of the two parties to the connection, and exchange TCP window size information. In socket programming, when a client executes connect(). Three handshakes are triggered.

Breaking a TCP connection requires sending four packets, so it’s called a four-way handshake. The client or server can initiate the waving action. In socket programming, either side can perform close() to generate the waving action.

HTTP cache

The browser cache has the following features:

  1. Reduce redundant data transmission
  2. Reduce server load
  3. Speed up page loading on the client

Strong cache

Strong caching is controlled using the Expires and cache-control fields in the HTTP header, which indicate how long a resource will be cached. In a strong cache, a normal refresh ignores it, but does not clear it, requiring a forced refresh. The browser forces a refresh, and the request carries cache-control :no-cache and Pragma:no-cache

Negotiate the cache

Negotiated caching means that the server determines whether the cache resource is available, so the client and the server need to communicate through some identity, so that the server can determine whether the requested resource can be cached.

Normal refresh will enable weak cache and ignore strong cache. Strong caching is only enabled when you enter a url in the address bar or favorites, or refer to a resource through a link, etc. This is why sometimes when you update an image or js file, the page content is still old, but when you directly access the image or file in the browser, the content is new.

This involves two sets of header fields: Etag and if-none-match, last-Modified and if-modified-since. The unit of if-none-match is second. It is impossible to use if-none-match in fine-grained scenarios. Therefore, the Etag field is used to Match if-none-match.

webpack

Analysis tools

Packet size analysis

Webpack-bundle-analyzer is a packaging analyzer that allows you to see the size of each package and whether any packages are being repackaged.

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
​
const config = {
  plugins: [
    new BundleAnalyzerPlugin(),
  ]
}
Copy the code

Packing speed analysis

The speed-measur-webpack-plugin allows us to analyze the total packaging time and the time taken to build each loader and plugins to quickly locate configurations that can be optimized for WebPack.

const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
module.exports = (production) = > {
  if (production) {
    const endProdConfig = merge(commonConfig, prodConfig);
    return smp.wrap(endProdConfig);
  } else {
    const endDevConfig = merge(commonConfig, devConfig);
    returnsmp.wrap(endDevConfig); }};Copy the code

Volume optimization

Webpack4.0 supports code compression by default in production environments, i.e. mode=production mode.

JS compressed

const TerserPlugin = require('terser-webpack-plugin');
const config = {
  optimization: {
    minimize: true.minimizer: [
      new TerserPlugin(),
    ],
  },
}
Copy the code

CSS compression

We can compress CSS with the optimize- CSS-assets – WebPack-Plugin. The default compression engine is CSsnano.

const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const prodConfig = {
  optimization: {
    minimizer: [
      new OptimizeCSSAssetsPlugin({
        assetNameRegExp: /\.optimize\.css$/g,
        cssProcessor: require('cssnano'),
        cssProcessorPluginOptions: {
          preset: ['default', { discardComments: { removeAll: true}}],},canPrint: true,})]},}Copy the code

Image compression

It’s easy to use, we just add image-webpack-loader after file-loader.

const config = {
  rules: [{test: /\.(png|jpg|gif)$/,
      use: [
        {
          loader: 'file-loader'.options: {
            name: '[name]_[hash].[ext]'.outputPath: 'images/',}}, {loader: 'image-webpack-loader'.options: {
            // Compression jpeg configuration
            mozjpeg: {
              progressive: true.quality: 65
            },
            // Use imagemin**-optipng to compress PNG, enable: false to disable
            optipng: {
              enabled: false,},// Use imagemin-pngQuant to compress PNG
            pngquant: {
              quality: '65-90'.speed: 4
            },
            // Compressed GIF configuration
            gifsicle: {
              interlaced: false,},// Enable webp to compress JPG and PNG images into WebP format
            webp: {
              quality: 75}}}]},]}Copy the code

summary

This article has looked at some ways to optimize front-end loading performance, from network loading to resource packaging, and there are a lot of things you can do.

At the end of the wave small advertising, need to push meituan can be swept below the code, school recruitment club recruitment oh ~