The front end optimization mainly depends on two points around the cache and network strong and weak strategy

What problem does VUE solve? Vue helps me solve the problem of DOM manipulation by using two-way data binding and virtual DOM technology without us thinking about how to manipulate DOM and how to operate DOM efficiently;

I. Optimization at the code level

1.1. Use scenarios are distinguished between computed and Watch

Computed: Computed attributes depend on other attribute values, and computed values are cached. Only when the dependent attribute values change, the computed values will be recalculated the next time it obtains computed values

Watch: It’s more of a “watch” function, something like a listening callback, where you do a callback every time something changes that you’re listening to and you’re doing something else. So if you want to do a numerical calculation, and you’re relying on other data, you should use computed, because you can take advantage of computed caching to avoid getting a value every time, It’s all recalculated;

Watch should be used when we need to perform asynchronous or expensive operations when data changes. Using the Watch option allows us to perform asynchronous operations (accessing an API), limits how often we perform that operation, and sets the intermediate state until we get the final result. These are all things you can’t do with computed properties.

1.2 V-for traversal Must add a key to the item and avoid using v-if at the same time

(1) V-for traversal must add key for item. During traversal rendering of list data, a unique key value should be set for each item to facilitate accurate finding of the list data by vue.js internal mechanism. When state is updated, the new state value is compared to the old state value to locate the DIFF faster.

V-for has a higher priority than V-if. If you need to traverse the entire array every time, it will affect the speed, especially if you need to render a small part of it. Replace it with computed property if necessary.

1.3 Long list performance optimization

Vue hijacks data via Object.defineProperty to make the view respond to data changes. However, sometimes our component is purely a data presentation and nothing will change. We don’t need Vue to hijack our data. This significantly reduces component initialization time, so how do we prevent Vue from hijacking our data? Freeze can be used to freeze an Object. Once the Object is frozen, it cannot be modified.

export default {
  data: () => ({
    users: {}
  }),
  async created() {
    const users = await axios.get("/api/users"); this.users = Object.freeze(users); }}; Optimization of infinite list performance reference https://www.cnblogs.com/imwtr/p/10428819.html big list a distinction between two core a fragment Specific implementation is divided into throttling rendering window only visible data function Reduce the VNode and Vue components reside, Instead of using the displayed subcomponent slot approach, manually create a virtual DOM to cut off object referencesCopy the code

1.4 Destruction of events

When a Vue component is destroyed, it automatically cleans up its connections to other instances and unties all its instructions and event listeners, but only for the component’s own events. If you use addEventListene and other methods in JS, they will not be automatically destroyed. We need to manually remove the listening of these events during component destruction to avoid memory leaks, such as

created() {
  addEventListener('click'.this.click, false)
},
beforeDestroy() {
  removeEventListener('click'.this.click, false)}Copy the code

1.5 Lazy Route loading

Vue is a single-page application, which may have a lot of routes introduced. In this way, the files packaged with WebPCAk are very large. When entering the home page, too many resources are loaded, and the page will appear white screen, which is not conducive to user experience. It would be much more efficient if we could split the components corresponding to different routes into different code blocks and then load the components only when the routes are accessed. This will greatly speed up the first screen, but may slow down the rest of the page

Route lazy loading:

const Foo = () => import('./Foo.vue')
const router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo }
  ]
})

Copy the code

1.6 Introduction of third-party plug-ins on demand

We often need to introduce third party plug-ins in a project. If we introduce the whole plug-in directly, it will cause the project to become too large. We can use babel-plugin-Component to reduce the size of the project by introducing only the required components. Install babel-plugin-component NPM install babel-plugin-component -d 2) install babel-plugin-component -d

{
  "presets": [["es2015", { "modules": false }]],
  "plugins": [["component",
      {
        "libraryName": "element-ui"."styleLibraryName": "theme-chalk"}}]]Copy the code

(3) Introduce some components in main.js:

import Vue from 'vue';
import { Button, Select } from 'element-ui';

 Vue.use(Button)
 Vue.use(Select)

Copy the code

1.7 Server Rendering SSR

Server-side rendering refers to the process of Vue rendering the entire HTML fragment of the tag on the client side at the server side. The HTML fragment formed by the server side is directly returned to the client side. This process is called server-side rendering. (1) Advantages of server-side rendering:

Better SEO: Because the content of SPA page is obtained through Ajax, and the search engine crawl tool does not wait for the completion of Ajax asynchronism before grabbing the page content, so the content of SPA page obtained through Ajax cannot be captured; SSR is directly returned by the server to the rendered page (data has been included in the page), so the search engine crawler can grab the rendered page;

Faster content arrival time (faster loading on the first screen) : SPA will wait for all Vue compiled JS files to be downloaded before rendering the page. File download takes a certain amount of time, so rendering on the first screen takes a certain amount of time. SSR directly returns the page rendered by the server directly, without waiting to download JS files and render again, so SSR has a faster content arrival time

(2) Disadvantages of server-side rendering:

More development constraints: for example, server-side rendering only supports the beforCreate and Created hook functions, resulting in some external extension libraries requiring special handling to run in server-side rendering applications; And unlike fully static single-page application SPA, which can be deployed on any static file server, server-side rendering applications need to be in the Node.js server running environment; Nuxt frame ()

Second, optimization of Webpack level

2.2 Reduce redundant code from ES6 to ES5

Install Babel - plugin - transform - runtime:Copy the code

2.3. Extract common code

Webpack has built-in plugin CommonsChunkPlugin which is specially used to extract the common parts of multiple chunks. The configuration of CommonsChunkPlugin in our project is as follows:Copy the code

2.4 Precompiling templates

When using a template in the DOM or a string template in JavaScript, the template is compiled into a rendering function at run time. This is usually fast enough, but it is best avoided in performance-sensitive applications. The easiest way to precompile a template is to use a single file component — the relevant build Settings take care of the precompilation automatically, so the built code already contains the compiled renderers instead of the original template strings. If you use Webpack and prefer to separate JavaScript and template files, you can use vue-template-loader, which also converts template files into JavaScript rendering functions during build.

2.5 optimize SourceMap

After the project is packaged, we will package multiple files and codes under development into one file. After compression, removing redundant Spaces and Babel compilation, the compiled code will be used in the online environment. Then the code after such processing will be very different from the source code. We can only locate the compressed code, not the code in the development environment. It is bad for development to tune the problem, hence sourceMap, which is designed to solve the problem. Cheap -module-eval-source-map

Recommended production environment: cheap-module-source-map

2.6 Output analysis of construction results

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin =   require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}

Copy the code

2.7 Removing useless code by Tree shaking unused modules.

Basic Web technology

Common use of enabling GZIP browser cache CDN use Chrome Performance to find Performance bottlenecks