HTTP optimization

Gzip compression

Compression and consolidation of resources

Gzip encoding over THE HTTP protocol is a technique used to improve the performance of Web applications, and both web servers and clients (browsers) must support GZIP.

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

Should you use Gzip

The server takes time to compress Gzip; Extracting Gzip takes time for the browser. The transmission time saved in the middle is really that significant? Gizp is recommended for larger files

Enable 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, / / processing is greater than the value of the resources. Only by bytes minRatio: 0.8 // Only resources with a compression ratio less than this value are processed deleteOriginalAssets: false,}),];Copy the code

Configure the CompressionWebpackPlugin in detail

The CDN to accelerate

Now most cloud service providers provide CDN services

Simply put: data on the original server is copied to other servers. When users access the data, that server accesses the data on that server.

The advantages of CDN acceleration are low cost and fast speed. CDN Best can be used for acceleration, free, private and public CDN system can be deployed. Can realize downtime detection, automatic switch IP, sub-line, group resolution. That is, the main role of CDN acceleration is to ensure the normal access of the website, and speed up the website access and response speed, to prevent the website due to hacker attacks, DNS resolution hijacking failure caused by the website server downtime.

Image (icon) aspect

Use font ICONS

Recommended: Iconfont- Alibaba Vector icon library

Sprite figure

Integrate multiple ICONS together

Sprite images are difficult to make, so I recommend Iconfont instead

Image Base64 encoding to reduce page requests (small images recommended)

Base64 encoded images display themselves in the browser

< span style =” max-width: 100%; clear: both; min-height: 1em; You can do the same with CSS backgrounds

Use Webpack to process the image into Base64
npm install --save-dev url-loader // webpack.config.js module.exports = { module: { rules: [{ test: / \. (PNG | SVG | JPG | | jpeg GIF | ico | woff | woff2 | eot | the vera.ttf | otf) $/, use: [{loader: "url - loader", / / the size according to the pictures, the image optimization into base64 options: {limit: 10000, // base64 for images smaller than 10000 bytes}}]}]}};Copy the code
Webpack configures compression for JPG, PNG, GIF, and SVG images
// webpack.config.js module.exports = {module: {rules: [{loader: "image-webpack-loader", // let's go back to webpack.config.js module. Exports = {module: {rules: [{loader: "image-webpack-loader", // let's go back to webpack.config.js module. { mozjpeg: { progressive: true, quality: 65, }, optipng: { enabled: false, }, pngquant: { quality: "65-90", speed: 4, }, gifsicle: { interlaced: false, }, webp: { quality: 75, }, }, }, ], }, };Copy the code

HTML, CSS optimization

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, < span style = "box-sizing: border-box! Important; word-wrap: break-word! Important;" <style> /** * for (let I =0; i < 1000000000000000; I++) {console.log(" young people don't speak code! } </script> </head> <body> <div id="container"></div> / */ <script> var container = document.getelementByid ("container") console.log('container', Container) // '<div id="container"></div>' </script> </body> /** * */ <style>... <style> </html>Copy the code
Refluxing and repainting

The browser rendering mechanism is required, so this article will not be covered

Reflux (rearrangement)

Backflow, also known as rearrangement, refers to a rendering where geometric properties need to be changed. Triggers browser backflow and regenerates the render tree.

redraw

Redraw refers to rendering that changes appearance attributes without affecting geometry. Nodes in the render tree change without affecting the geometry of the node.

  • Geometric properties: including layout, size and other properties that can be measured by mathematical geometry
Layout: display, float, position, list, table, flex, columns, grid size: margin, padding, border, width, heightCopy the code
  • Appearance attributes: include interface, text and other attributes that can be described by state vectors
Interface: Appearance, outline, background, mask, box-shadow, box-reflect, filter, opacity, clip text: text, font, wordCopy the code

Js optimization

Reduce DOM manipulation
  • Reduce operations such as DOM changes
// 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 = contentCopy the code
  • DocumentFragment

Is not a real DOM tree, and its changes do not cause the DOM tree to be re-rendered

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) // Generate the DOM operation box. AppendChild (content)Copy the code
Lazy loading of images
<li><img src="img/loading.gif" data-src="img/1.jpg"></li>
Copy the code

Loading. GIF is used for each image in the beginning, which saves multiple image requests when loading the first screen

How it works: When the scroll bar is set to an image, the normal image in data-src is loaded

Specific implementation can see my previous article to achieve lazy loading pictures

Anti-shake and throttling
Anti – shake: trigger only once in a certain period of time
/** * @param {Function} func Callback Function to be executed * @param {Number} Wait delay * @param {Boolean} immediate Whether to execute immediately * @return null */  let timer, flag; function throttle(func, wait = 500, immediate = true) { if (immediate) { if (! flag) { flag = true; Typeof func === 'function' && func(); // If immediate, typeof func === 'function' && func(); timer = setTimeout(() => { flag = false; }, wait); } } else { if (! Flag) {flag = true // If the execution is not immediate, Timer = setTimeout(() => {flag = false Typeof func === 'function' && func(); }, wait); }}}; export default throttleCopy the code
Throttling: Execute a function only after a wait of milliseconds for the last operation
let timeout = null; /** * @param {Function} func Callback Function to be executed * @param {Number} Wait delay * @param {Boolean} immediate Whether to execute immediately * @return null */ Function debounce(func, wait = 500, immediate = false) {// Clear the timer if (timeout! == null) clearTimeout(timeout); If (immediate) {var callNow =! timeout; timeout = setTimeout(function() { timeout = null; }, wait); if (callNow) typeof func === 'function' && func(); } else {// Set timer, timeout will not be cleared after the last operation, Timeout = setTimeout(function() {typeof func === 'function' && func(); }, wait); } } export default debounceCopy the code

Webpack4 optimizations (optimizations such as excessive packaging)

Webpack sets CDN optimization

Vuecli generated items for configuration

Run YARN Build and find vue, vuex, vuE-router in vUE, vVs. js. Now we can do vUE via externals of webpack, vuex is extracted using CDN

# vue.config.js module.exports = { configureWebpack:{ externals: { 'vue': 'Vue', 'vuex': 'Vuex' } } } # store/index.js import Vuex from "vuex"; // Vue.use(Vuex); Comment out theCopy the code
// 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 SRC = "https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.min.js" > < / script > < script SRC = "https://cdn.bootcdn.net/ajax/libs/vuex/3.1.3/vuex.min.js" > < / script > < / body >Copy the code
splitChunks

Run YARN build and find vue-routers in vendors. Js that need to be separated using splitChunks in webpack

The configuration of splitChunks is quite complicated and needs to be learned 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,
          }
        },
      },
    },
  },
};
Copy the code

Related blog

Play with the artistic beauty of CSS