preface

This paper summarizes the methods of front-end performance optimization. If you have different views on the answer, please kindly add the discussion in the comments section. Of course, you are also welcome to point out the questions in the comments section.

What is performance?

For the front end, it consumes all the resources of the browser and server from the time the site is generated to the time the code runs

How to optimize performance

1. Cache strategy

2. Refine YOUR JS code

It’s about using optimal algorithms to reduce time and space complexity

3. Static resource loading

(1) the CDN

For example, the Vue project introduces the Element component library

<! -- Introducing styles -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> 
<! -- Introducing a component library --> 
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
Copy the code

(2) Load images and other resources

  • Sprite image or Sprite image: Place all the small images on a large image. When using, directly reference the large image to locate

    • You can use the Webpack plug-in: webpack-spritesmith
    • The program automatically reads the files in the Sprite image directory and combines all the images into one large image
  • Lazy loading of images: load on demand

    • The vue-lazy-load plug-in can be used
    //main.js
    import Vue from 'vue'
    import App from './App.vue'
    import VueLazyload from 'vue-lazyload'
    
    Vue.use(VueLazyload)
    
    // or with options
    Vue.use(VueLazyload, {
      preLoad: 1.3.error: 'dist/error.png'.loading: 'dist/loading.gif'.attempt: 1
    })
    
    new Vue({
      el: 'body'.components: {
        App
      }
    })
    Copy the code
    • Change the image binding v-bind: SRC to V-lazy in the vue file
    <ul>
      <li v-for="img in list">
        <img v-lazy="img.src" >
      </li>
    </ul>
    Copy the code

4. Optimized vUE framework code

  • The rational use ofv-ifv-show
  • The rational use ofcomputedwatchandfilter
  • Try to reduce the use of Watch to monitor corresponding data. Excessive monitoring data will lead to performance consumption and system lag. Use event central bus or VUEX for data change operations.
  • v-forTraversal foritemaddkeyv-forTraversal avoid simultaneous usev-if
  • Subdivide components: Write the layout of all components in one component. When data changes, vuejs’s data-driven view is slow to update due to the large component code, resulting in slow rendering
  • When not in use, remove timers and listeners removeEventListener or clearInterval in the component destruction phase (beforeDestory)
  • Keep-alive cache component, Props:
    • include– String or regular expression. Only components with matching names are cached.
    • exclude– String or regular expression. Any component with a matching name will not be cached.
    • max– digital. Maximum number of component instances can be cached.
  • Lazy route loading: There are three methods
  • SSR server rendering: the limitation is that currently only support Koa, Express and other Nodejs background framework
  • Tree-shaking: Remove useless code

5. Webpack level optimization

(1) Development environment performance optimization

  • Optimize packaging build speed:

    • HMR: Hot Module replacement. When a module changes, only this module is packaged
  • Optimized code debugging

    • Optimized code debugging source-map: Can locate code errors

(2) Production environment performance optimization

  • Tree-shaking Webpack: Removing useless code
Premise:1.You must use ES6 modularity2.Enable the Production environment: Reduce the code size configured in package.json"sideEffects": falseProblem: CSS / @babel/polyfill files might get wiped out"sideEffects": ["*.css"."*.less"] This will preserve CSS, less filesCopy the code
  • Webpack modules are lazily loaded/preloaded
console.log('index.js file loaded ~');

// import { mul } from './test';

document.getElementById('btn').onclick = function() {
  // Lazy loading ~ : files are loaded only when they are needed ~ ---- but when a module is used and the module is very large, the loading will be slow
  // Prefetch: js files will be loaded in advance before being used. When used, the cache will be read ---- poor compatibility
  // Normal loading can be considered parallel loading (multiple files are loaded at the same time)
  // Prefetch: Wait until other resources are loaded and the browser is free, then secretly load the resources
  import(/* webpackChunkName: 'test', webpackPrefetch: true */'./test').then(({ mul }) = > {
    console.log(mul(4.5));
  });
};
Copy the code
  • PWA Progressive Web development application (accessible offline)
    • When offline, resources are obtained from serviceWorker and CacheStorage

In a real project, when the route has jumped but the request of the previous page is still pending, it is ok if the data volume is small, but when the data volume is large, the new page will be jumped but the old request is still not stopped, which will greatly reduce the performance. In this case, we should cancel the request before getting the corresponding request, and then jump to the page. Axios gives us a way to do this:

cancelToken

Official website method one:

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // Processing error}});// Cancel the request (the message argument is optional)
source.cancel('Operation canceled by the user.');
Copy the code

If I want to jump to a page, I call source.cance() to kill the uncompleted request. The downside of this method, however, is that it is cumbersome to manually call source.cance() each time. How to achieve global unified management?

Official website method two:

CancelToken can also be created by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // The executor function takes a cancel function as an argumentcancel = c; })});// Cancel the request
cancel();
Copy the code

According to this method: let’s implement it step by step:

Void httpRequestList (httpRequestList); void httpRequestList (httpRequestList); void httpRequestList (httpRequestList); void httpRequestList (httpRequestList);

// main.js
Vue.$httpRequestList = []
Copy the code

2. Add an httpRequestList array to each of our wrapped POST and GET requests: each request contains a cancelToken object.

POST (url, data, errMsg) {
    const CancelToken = axios.CancelToken
    return axios.post(url, data, {
      timeout: 30000.cancelToken: new CancelToken(function executor (c) {
        Vue.$httpRequestList.push(c)
      })
    }).then(checkStatus).then(res= > checkCode(res, errMsg))
  },
  GET (url, params, errMsg) {
    const CancelToken = axios.CancelToken
    return axios.get(url, {
      params: {
        _t: + (new Date()),
        ...params
      },
      timeout: 30000.cancelToken: new CancelToken(function executor (c) {
        Vue.$httpRequestList.push(c)
      })
    }).then(checkStatus).then(res= > checkCode(res, errMsg))
  }
Copy the code

3. After that we’ll write a method that executes the cancel method:

import Vue from 'vue'

export const clearHttpRequestingList = () = > {
  if (Vue.$httpRequestList.length > 0) {
    Vue.$httpRequestList.forEach((item) = > {
        //item is the cancel method that loaded each request into the httpRequestList array.
        // If the request is pending, cancel it. Remember to clear the httpRequestList array when you're done.
      item()
    })
    Vue.$httpRequestList = []
  }
}
Copy the code

4. Finally we go back to main.js and execute clearHttpRequestingList() before each jump.

router.beforeEach((to, from, next) = >{ clearHttpRequestingList() .......... Here is your route verification code.......... })Copy the code

In this way, the previous requests in the pending state are cleared before each route jump, optimizing performance.

conclusion

Feel good writing, helpful to you, you can share with people around you, the more you share knowledge, do not be stingy

Follow-up update other front-end knowledge summary, please pay attention to me, tidy up, share with you, we learn front-end together