Refining functions: Avoid the occurrence of large functions, independent functions are easier to be copied and code reuse

Juejin. Cn/post / 684490…

Principle: use more memory, cache and other methods, reduce CPU calculation, reduce network loading time namely a concept of space for time

Make loading and rendering faster

Loading:

  • Reduce resource volume: compress code
  • Control concurrent requests: reduce access times: merge code, SSR server rendering
  • Use a faster network: CDN

Render:

  • File placement: CSS in head, JS under body
  • Lazy loading: Lazy loading of components/routes
  • Caching: Caching DOM queries, frequent DOM operations, merging together and inserting DOM structures
  • Throttling and anti-shaking

Cache policies: Expires, cache-control,

Last-modified/if-modified-since: The local cache has not expired

Etag/ F-none-match: Cache expired

Contenthash is used in Webpack to calculate the hash based on the content of the file. If the content of the file remains unchanged, the hash, URL, url, and file remain unchanged will automatically trigger the HTTP cache mechanism and return 304

Vue code level optimization

Coding phase

  • Minimize the amount of data in data. Getter and setter are added to all data in data, and the corresponding Watcher is collected
  • V-if and V-for cannot be used together
  • Use the event broker if you need to use V-for to bind events to each element
  • The SPA page uses the keep-alive cache component
  • In more cases, use v-if instead of V-show
  • Key guarantees uniqueness
  • Use routing lazy load, asynchronous components
  • Anti-shake and throttling
  • Import third-party modules as required
  • Long lists scroll to visual area for dynamic loading

Lazy loading of images

SEO optimization

  • pre-rendered
  • Server rendering SSR

Packaging optimization

  • The compression code
  • Tree Shaking/Scope Hoisting
  • Load third-party modules using CDN
  • Multithreaded package Happypack
  • SplitChunks removes public files
  • SourceMap optimization

The user experience

The skeleton screen PWA can also use caching (client cache, server cache) optimization, server enable GZIP compression, and so on

Use v-if, V-show wisely

Fair use Computed

Add key to V-for to avoid using the key at the same time with V-if

Use asynchronous components wisely

Use the cache component keep-alive properly

Data level should not be too deep: resulting in more depth of calculation in response mode during listening and more positioning times, which will lead to page lag

Using vue-loader to compile templates in a development environment?

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 can significantly reduce component initialization time by using Object.freeze

export default { data: () => ({ users: {} }), async created() { const users = await axios.get("/api/users"); this.users = Object.freeze(users); }};
Copy the code

Custom event, DOM event timely destruction: When a Vue component is destroyed, it will automatically clean up its connection to other instances and unbind 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 for these events when the component is destroyed to avoid memory leaks

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

Use route lazy loading: It is more efficient to split the components corresponding to different routes into different code blocks and 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

Optimization at the WebPack configuration level

Reduce redundant code from ES6 to ES5

The Babel plug-in will inject some helper functions when converting ES6 code to ES5 code, such as the following ES6 code:

class HelloWebpack extends Component{… }

The following two helper functions are needed to convert this code into working ES5 code:

Babel - the runtime/helpers/createClass / / used to implement the class grammar Babel - the runtime/helpers/inherits / / used to implement the extends the syntaxCopy the code

By default, Babel will embed the dependent helper function code in each output file. If multiple source files rely on these helper functions, the helper function code will appear many times, resulting in code redundancy. To solve this you can pass by relying on them

Require (‘ Babel – the runtime/helpers/createClass) way to import,

So you can only make them appear once. The babel-plugin-transform-Runtime plugin is used to reduce the file size of Babel compiled code by replacing relevant helper functions with import statements. After installing the plugin, modify the.babelrc configuration file to

“plugins”: [“transform-runtime”]

Extract common code

If the third party libraries and common modules for each page are not extracted from the project, the project will have the following problems:

  • The same resources are loaded repeatedly, wasting user traffic and server costs.
  • Too many resources need to be loaded on each page. As a result, the first screen of a web page loads slowly, affecting user experience

Therefore, it is necessary to separate the common code into separate files to optimize the above problems. Webpack has built-in plug-in CommonsChunkPlugin, which is specially used to extract the common part of multiple chunks. The CommonsChunkPlugin in the project is configured as follows

Optimize SourceMap

After the project is packaged, multiple file codes under development will be packaged into one file, and 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. When there are bugs, 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

Here’s why:

  • Cheap: The column information in the source code is of no use, so we do not want the packaged file to contain column-related information, only the row information to establish the dependencies before and after the package. Therefore, in both development and production environments, we want to add the base type cheap to ignore column information before and after packaging;
  • Module: In both development and formal environments, we want to locate the source code of the bug. For example, a Vue file reported an error. We want to locate the Vue file, so we also need the Module configuration.
  • Soure-map: Source-map generates a separate Soucemap file for each packaged module, so we need to add the source-map attribute;
  • Eval-source-map: Eval is very fast to package code because it does not generate a map file, but you can use eval-source-map on an EVAL combination to store the map file as a DataURL in a packaged JS file. Do not use eval-source-map in a formal environment because it increases the file size, but in a development environment, try it out because they pack quickly

Build results output analysis

The code output from Webpack was very unreadable and the files were very large, which gave us a headache. In order to analyze the output more easily and intuitively, a number of visual analysis tools have emerged in the community. These tools graphically present the results more visually, allowing us to quickly understand the problem. In the webpack-bundle-Analyzer project, webpack.prod.conf.js is configured:

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

The analysis report is generated after executing $NPM run build –report

Enable Gzip compression

Compression -webpack-plugin, in webpack.prod.conf.js

After the configuration, run the build command. You can find that a new file with the suffix gz is added to the generated static file

If you deploy your project to a gzip enabled server such as Nginx at this point, you can visit the browser and see that the browser downloaded the compressed file

The server configures gzip only to be compatible with this format. It can read this format, but compression into Gzip still needs to be done by the front end. 2: The server sends gzip to the browser, which knows the format and can read it

Basic Web technology level optimization

Browser cache

In order to improve the speed of user loading pages, it is very necessary to cache static resources. According to the classification of whether to re-send requests to the server, HTTP cache rules are divided into two categories (mandatory cache, comparative cache).

The use of CDN

When a browser downloads CSS, JS and images from a server, it has to connect to the server. Most servers have limited bandwidth. CDN can load files through different domain names, so that the number of concurrent connections to download files is greatly increased, and CDN has better availability, lower network delay and packet loss rate

Use Chrome Performance to find Performance bottlenecks

Chrome’s Performance panel records js execution details and times over a period of time. To analyze page performance using Chrome Developer Tools, perform the following steps.

  1. Open Chrome Developer Tools and switch to the Performance panel
  2. Click Record to start recording
  3. Refresh the page or expand a node
  4. Click Stop to Stop recording