Front end optimization (webpack, JS, HTML)

Time:2021-3-3

HTTP optimization

Gzip compression

Compression and combination of resources

Gzip coding on HTTP protocol is a technology used to improve the performance of web applications. Web server and client (browser) must support gzip together.

The browser requests the URL and sets the property accept in the request header- encoding:gzip . It indicates that the browser supports gzip.

Should gzip be used

It takes time for the server to compress gzip, and it takes time for the browser to decompress gzip. Is the transmission time saved in the middle really so considerable? It is recommended to use large files for gizp

Starting gzip compression in webpack4
npm i -D compression-webpack-plugin

plugins: [
  new CompressionPlugin({
    filename: "[path].gz[query]",
    algorithm: "gzip",
    test: /\.js$|\.html$|\.css/,
    Threshold: 10240, // only processes resources larger than this value. By byte
    Minratio: 0.8 // only resources with lower compression ratio will be processed
    Deleteoriginalassets: false, // delete the original resource
  }),
];

Detailed configurationCompressionWebpackPlugin

CDN acceleration

Now most cloud service providers provide CDN services

Front end optimization (webpack, JS, HTML)

To put it simply: the data on the original server is copied to other servers. When the user accesses, the server accesses the data on that server.

Advantages of CDN accelerationIt’s low cost and fast. It can be accelerated with CDN best CDN, free of charge, and can deploy private and public CDN systems. Can achieve downtime detection, automatic switching IP, line, packet analysis. In other words, the main function of CDN acceleration is to ensure the normal access of the website, speed up the website access speed and response speed, and prevent the website server downtime caused by hacker attacks, DNS resolution hijacking failure.

Picture (icon) aspect

Use Font Icon

recommend:Icomont Alibaba vector icon library

Sprite

Integrate multiple icons together

It’s troublesome to make sprite image. I still recommend the font icon of iconfont

Pictures using Base64 encoding to reduce the number of page requests (suggest small pictures)

Base64 encoded images can be displayed in the browser itself

Using Base64 encoding to embed the image directly into the web page, instead of loading it from the outside, such as< imgurl loader ", // optimize the image to Base64 according to the image size
options: {
Limit: 10000, // Base64 operation is performed for images less than 10000 bytes
}
}
]
}]
}
};

Webpack configures the compression of JPG, PNG, GIF and SVG images
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        Loader: "image webpack loader" // optimize the image first
        options: {
          mozjpeg: {
            progressive: true,
            quality: 65,
          },
          optipng: {
            enabled: false,
          },
          pngquant: {
            quality: "65-90",
            speed: 4,
          },
          gifsicle: {
            interlaced: false,
          },
          webp: {
            quality: 75,
          },
        },
      },
    ],
  },
};

HTML, CSS optimization

< script > tags and < style > tags (see comments)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  /**
  *Put the head: the page first parses < style > and then gets CSS and then parses HTML
  */
  <style>...<style>
  /**
  *Put the head: when the page parsing encounters JS, it needs to run JS before it can continue
  *Disadvantages: once JS is loaded or operated for a long time, it will cause the user white screen
  */
  <script>
    for (let i=0; i < 1000000000000000; i++) {
        console.log "Young people don't talk code! Just wait for a while. ")
    }
  </script>
</head>
<body>
  <div id="container"></div>
  /**
  *Put the tail: after parsing the page, start loading JS
  *Advantages: users can see the interface without waiting for JS to load
  */
   <script>
    var container = document.getElementById("container")
    console.log('container', container) // '<div id="container"></div>'
  </script>
</body>
  /**
  *Put the tail: the page parses HTML first and then gets parsed CSS
  *Disadvantages: the HTML node does not have style until it comes out
  */
  <style>...<style>
</html>
Reflow and redraw

Need browser rendering mechanism, this article will not expand

Backflow (rearrangement)

Reflow, also known as rearrangement, refers to the rendering whose geometric properties need to be changed.Trigger browser reflow and regenerate rendering tree

Repaint

Redraw refers to the rendering that changes appearance properties without affecting geometric properties.The node of the rendering tree changes, but the geometric properties of the node are not affected

  • Geometric attributes: including layout, size and other attributes that can be measured by mathematical geometry
Layout: display, float, position, list, table, flex, columns, grid
Dimensions: margin, padding, border, width, height
  • Appearance attributes: including interface, text and other attributes that can be described by state vector
Interface: appearance, outline, background, mask, box shadow, box reflect, filter, opacity, clip
Text: text, font, word

JS optimization

Reduce DOM operations
  • Reduce DOM changes and other operations
// bad
let box = document.getElementById('box')

box.innerHTML = '1'
box.innerHTML += '2'
box.innerHTML += '3'
...

// good
let content = ''
content = '1'
content += '2'
content += '3'

box.innerHTML  =Content // insert once
  • DocumentFragment

It is not a real DOM tree, and its changes will not cause a re rendering of the DOM tree

let box = document.getElementById('box')

let content = document.createDocumentFragment()

let Fdiv = document.createElement('div')

Fdiv.innerHTML = '1'
Fdiv.innerHTML += '2'
Fdiv.innerHTML += '3'

content.appendChild(Fdiv)
//Only one DOM operation is generated
box.appendChild(content)
Image lazy loading
<li><img src="img/1.jpg"></li>

In the beginning, every picture was used loading.gif When the first screen is loaded, multiple picture requests can be saved

principle: load the normal picture in data SRC when the scroll bar is set to the picture

Specific implementation can see my previous articleRealize lazy loading of pictures

Anti shake and throttling
Anti shake: in a certain period of time, it can only be triggered once
/**
 *@ param {function} func the callback function to execute 
 *Delay time of @ param {number} wait
 *Do you want to execute @ param {Boolean} immediate immediately
 * @return null
 */
let timer, flag;
function throttle(func, wait = 500, immediate = true) {
    if (immediate) {
        if (!flag) {
            flag = true;
            //If it is executed immediately, it is executed when it starts within wait milliseconds
            typeof func === 'function' && func();
            timer = setTimeout(() => {
                flag = false;
            }, wait);
        }
    } else {
        if (!flag) {
            flag = true
            //If it is not executed immediately, it is executed at the end of wait milliseconds
            timer = setTimeout(() => {
                flag = false
                typeof func === 'function' && func();
            }, wait);
        }
        
    }
};
export default throttle
Throttling: within a certain period of time, only the last operation, and then wait milliseconds before the function is executed
let timeout = null;
/**
 *@ param {function} func the callback function to execute 
 *Delay time of @ param {number} wait
 *Do you want to execute @ param {Boolean} immediate immediately 
 * @return null
 */
function debounce(func, wait = 500, immediate = false) {
    //Clear timer
    if (timeout !== null) clearTimeout(timeout);
    //Immediate implementation, such cases are generally not used
    if (immediate) {
        var callNow = !timeout;
        timeout = setTimeout(function() {
            timeout = null;
        }, wait);
        if (callNow) typeof func === 'function' && func();
    } else {
        //Set the timer, when the last operation, the timeout will not be cleared, so the func callback method will be executed after the wait millisecond delay
        timeout = setTimeout(function() {
            typeof func === 'function' && func();
        }, wait);
    }
}

export default debounce

Webpack4 optimization

Setting up CDN optimization in webpack

The project generated by vuecli is configured

Run yarn build to discover vendors.js It includes Vue, vuex and Vue router
Now we can use webpack’s externals for Vue. Vuex can use CDN instead

# vue.config.js
module.exports = {
  configureWebpack:{
    externals: {
       'vue': 'Vue',
       'vuex': 'Vuex'
    }
  }
}

# store/index.js
import Vuex from "vuex";

//  Vue.use (vuex); comment out
// index.html
<body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
    <script></script>
    <script></script>
  </body>
Split chunks

Run yarn build to discover vendors.js There is also Vue router to be separated
It can be segmented by using split chunks in webpack

The configuration of split chunks is very complex. You need to learn by yourself. I just provide a solution

# vue.config.js
module.exports = {
  configureWebpack: {
    optimization: {
      splitChunks: {
        cacheGroups: {
          vendors: {
            test: /node_modules/,
            chunks: "initial",
            minChunks: 1,
            priority: -10,
          },
          router: {
            name: 'chunk-router',
            test: /[\/]node_modules[\/]vue-router[\/]/,
            chunks: "all",
            minChunks: 1,
            priority: -5,
          }
        },
      },
    },
  },
};

Related blog

The artistic beauty of CSS

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]