In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on the "Vue project performance optimization method tutorial", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn the "Vue project performance optimization method tutorial" it!
1. Optimization at the code level
1.1distinguishing usage scenarios from v-if and v-show
V-if is true conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during switching; it is also lazy: if the condition is false at the initial rendering, nothing is done-the conditional block does not begin to render until the condition becomes true for the first time.
V-show is much simpler. No matter what the initial condition is, the element is always rendered and simply switched based on the display attribute of CSS.
Therefore, v-if is suitable for scenarios where conditions are rarely changed at runtime and do not need to switch conditions frequently, while v-show is suitable for scenarios where conditions need to be switched very frequently.
1.2distinguishing usage scenarios from computed and watch
Computed: is a computed attribute that depends on other attribute values, and the value of computed is cached. Only when the value of the attribute it depends on changes, the value of computed will be recalculated the next time you get the value of computed.
Watch: it is more like the function of "observation", which is similar to the monitoring callback of some data. Callbacks are performed for subsequent operations whenever the monitored data changes.
Apply scenarios:
When we need to do numerical calculations and rely on other data, we should use computed because we can take advantage of the cache feature of computed to avoid having to recalculate every time we get a value.
When we need to perform asynchronous or expensive operations when the data changes, we should use watch, using the watch option to allow us to perform asynchronous operations (accessing an API), limit how often we perform the operation, and set the intermediate state before we get the final result. These are things that computational properties cannot do.
1.3.The v-for traversal must add key to the item and avoid using v-if at the same time
(1) v-for traversal must add key for item
When traversing the list data, you need to set a unique key value for each item to facilitate the Vue.js internal mechanism to accurately find the list data. When state is updated, the new state value is compared with the old state value and is quickly located to the diff.
(2) v-for traversal to avoid using v-if at the same time
V-for has a higher priority than v-if, and if you need to traverse the entire array each time, it will affect the speed, especially if it needs to render a small part, it should be replaced with the computed attribute if necessary.
Recommended:
{{user.name}} computed: {activeUsers: function () {return this.users.filter (function (user) {return user.isActive})} copy the code
Not recommended:
{{user.name}} copy the code
1.4. Long list performance optimization
Vue will hijack data through Object.defineProperty to respond to changes in data. However, sometimes our components are pure data display, and there will be no change, so we do not need Vue to hijack our data. In the case of a large amount of data display, this can significantly reduce the initialization time of components, so how to prevent Vue from hijacking our data? You can freeze an object through the Object.freeze method, and once the frozen object is frozen, it can no longer be modified.
Export default {data: () = > ({users: {}}), async created () {const users = await axios.get ("/ api/users"); this.users = Object.freeze (users);}}; copy code
1.5. Destruction of events
When a Vue component is destroyed, it automatically cleans up its connections to other instances and unbinds all of its instructions and event listeners, but only for events of the component itself. If addEventListene and other methods are used in js, they will not be destroyed automatically. We need to manually remove the listening for these events when the components are destroyed to avoid memory leaks, such as:
Created () {addEventListener ('click', this.click, false)}, beforeDestroy () {removeEventListener (' click', this.click, false)} copy the code
1.6. Lazy loading of picture resources
For pages with too many images, in order to speed up the loading speed of the page, we often need not to load the images that do not appear in the visual area, and wait until we scroll to the visual area before loading. This will not only greatly improve the page loading performance, but also improve the user experience. We used Vue's vue-lazyload plug-in in our project:
(1) install plug-ins
Npm install vue-lazyload-- save-dev copy code
(2) introduce and use in the entry file man.js
Import VueLazyload from 'vue-lazyload' copy code
And then directly use it in vue
Vue.use (VueLazyload) copy code
Or add custom options
Vue.use (VueLazyload, {preLoad: 1.3, error: 'dist/error.png', loading:' dist/loading.gif', attempt: 1}) copy the code
(3) change the src attribute of the img tag to v-lazy directly in the vue file, thus changing the image display mode to lazy load display:
Copy the code
The above is a simple use of the vue-lazyload plug-in. If you want to see more parameter options for the plug-in, you can check the github address of vue-lazyload.
1.7. Routing lazy loading
Vue is a single-page application, and many routes may be introduced, so 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 the user experience. If we can divide the components corresponding to different routes into different code blocks, and then load the corresponding components when the routes are accessed, it will be more efficient. This will greatly increase the speed of the first screen display, but maybe the speed of other pages will slow down.
Route lazy loading:
Const Foo = () = > import ('. / Foo.vue') const router = new VueRouter ({routes: [{path:'/ foo', component: Foo}]}) copy the code
1.8. On-demand introduction of third-party plug-ins
We often need to introduce third-party plug-ins in the project, if we directly introduce the whole plug-in, the volume of the project will be too large, we can use babel-plugin-component, and then we can only introduce the required components to achieve the purpose of reducing the volume of the project. The following is an example of introducing element-ui component library into the project:
(1) first, install babel-plugin-component:
Npm install babel-plugin-component-D copy code
(2) then, modify .babelrc to:
{"presets": [["es2015", {"modules": false}]], "plugins": [["component", {"libraryName": "element-ui", "styleLibraryName": "theme-chalk"}]} copy the code
(3) introduce some components into main.js:
Import Vue from 'vue'; import {Button, Select} from' element-ui'; Vue.use (Button) Vue.use (Select) copy the code
1.9. Optimize the performance of infinite lists
If your application has a very long or infinitely scrolling list, you need to use windowing techniques to optimize performance, rendering only a small number of areas and reducing the time it takes to re-render components and create dom nodes. You can optimize this infinite list scenario by referring to the following open source projects vue-virtual-scroll-list and vue-virtual-scroller.
1.10. Server rendering SSR or pre-rendering
Server rendering means that the entire html fragment rendered by Vue on the client side is done on the server side, and the html fragment formed by the server is directly returned to the client side. This process is called server rendering.
(1) advantages of server rendering:
Better SEO: because the content of the SPA page is obtained through Ajax, and the search engine crawl tool does not wait for the Ajax to complete asynchronously before crawling the page content, so in SPA, the content obtained by the page through Ajax cannot be crawled; while SSR is returned directly by the server to the rendered page (the data is already contained in the page), so the search engine crawling tool can crawl 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 starting to render the page, which takes a certain amount of time to download, etc., so the first screen rendering takes a certain amount of time; SSR is directly rendered by the server and the page is directly returned to display, so there is no need to wait for js files to be downloaded and to render again, so SSR has a faster content arrival time.
(2) disadvantages of server rendering:
More restrictions on development conditions: for example, server rendering only supports two hook functions, beforCreate and created, which will cause some external extension libraries to require special processing to run in server rendering applications; and unlike SPA, a completely static single-page application that can be deployed on any static file server, server rendering applications need to be in the Node.js server runtime environment
More server load: rendering a complete application in Node.js obviously takes up more CPU resources than server, which only provides static files, so if you expect to use it in a high-traffic environment, prepare the server load and use caching strategies wisely.
If your project's SEO and first-screen rendering are the key indicators for evaluating the project, then your project needs server-side rendering to help you achieve the best initial loading performance and SEO. For more information on how to implement Vue SSR, please refer to another article by the author, "Vue SSR trekking Journey". If your Vue project only needs to improve the SEO of a few marketing pages (e.g. /, / about, / contact, etc.), then you may need to pre-render and simply generate static HTML files for specific routes at build time (build time). The advantage is that it is easier to set up pre-rendering, and you can use your front end as a completely static site, and you can easily add pre-render using prerender-spa-plugin.
II. Optimization at the Webpack level
2.1.Compression of pictures by Webpack
In the vue project, except that you can set the limit size in url-loader in webpack.base.conf.js to process images, and convert images smaller than limit to base64 format, the rest do not do anything. So for some large image resources, when requesting resources, loading will be very slow. We can use image-webpack-loader to compress images:
(1) first, install image-webpack-loader:
Npm install image-webpack-loader-- save-dev copy code
(2) then, configure it in webpack.base.conf.js:
{test: /\. (png | jpe?g | gif | svg) (\?. *)? $/, use: [{loader: 'url-loader', options: {limit: 10000, name: utils.assetsPath (' img/ [name]. [hash: 7]. [ext]')}}, {loader: 'image-webpack-loader' Options: {bypassOnDebug: true,}}]} copy the code
2.2. reduce the redundant code from ES6 to ES5
The Babel plug-in injects helper functions when converting ES6 code to ES5 code, such as the following ES6 code:
Class HelloWebpack extends Component {...} copy the code
The following two helper functions are required when this code is then converted into functioning ES5 code:
Babel-runtime/helpers/createClass / / is used to implement class syntax babel-runtime/helpers/inherits / / to implement extends syntax copy code
By default, Babel embeds these dependent helper functions in each output file. If multiple source code files rely on these helper functions, the code of these helper functions will appear many times, resulting in code redundancy. In order not to repeat the code of these helper functions, you can import them through require ('babel-runtime/helpers/createClass') when you rely on them, so that you can make them appear only once. The babel-plugin-transform-runtime plug-in is used to achieve this function, replacing the relevant helper functions with import statements, thereby reducing the file size of the code compiled by babel.
(1) first, install babel-plugin-transform-runtime:
Npm install babel-plugin-transform-runtime-- save-dev copy code
(2) then modify the .babelrc configuration file to:
"plugins": ["transform-runtime"] copy code
If you want to see more details of the plug-in, you can check out the detailed description of babel-plugin-transform-runtime.
2.3. Extract common code
If the third-party libraries and common modules of each page are not extracted in the project, the project will have the following problems:
The same resources are loaded repeatedly, wasting user traffic and server costs.
The resources that need to be loaded on each page are too large, which leads to the slow loading of the first screen of the web page and affects the user experience.
So we need to extract the common code of multiple pages into separate files to optimize the above problems. Webpack has a built-in plug-in CommonsChunkPlugin designed to extract the common parts of multiple Chunk. The configuration of CommonsChunkPlugin in the project is as follows:
/ / all packages that are dependent on package.json are packaged into the vendor.js file. New webpack.optimize.CommonsChunkPlugin ({name: 'vendor', minChunks: function (module, count) {return (module.resource & & /\ .js $/ .test (module.resource) & & module.resource.indexOf (path.join (_ _ dirname,'.. / node_modules')) = = 0) }}), / / extract the mapping relationship of the code module new webpack.optimize.CommonsChunkPlugin ({name: 'manifest', chunks: [' vendor']}) copy the code
If you want to see more details of the plug-in, you can check out the detailed description of CommonsChunkPlugin.
2.4. Template pre-compilation
When you use a template in DOM or a string template in JavaScript, the template is compiled into a render function at run time. In general, this process is fast enough, but it is best to avoid this use for performance-sensitive applications.
The easiest way to precompile a template is to use a single-file component-the relevant build settings automatically process the precompilation, so the built code already contains the compiled rendering function instead of the original template string.
If you use webpack and like to separate JavaScript and template files, you can use vue-template-loader, which can also convert template files into JavaScript rendering functions during the build process.
2.5.Extract the CSS of the component
When using a single-file component, the CSS within the component is dynamically injected through JavaScript in the form of style tags. There is a little runtime overhead, which can lead to a "styleless content flicker (fouc)" if you use server-side rendering. Extracting the CSS of all components to the same file avoids this problem and allows CSS to be better compressed and cached.
Check out the respective documentation of the build tool to learn more:
Webpack + vue-loader (webpack template for vue-cli is pre-configured)
Browserify + vueify
Rollup + rollup-plugin-vue
2.6. optimize SourceMap
After the project is packaged, we will package multiple file codes in the development into one file, and after compression, removal of excess spaces, and babel compilation, the compiled code will eventually be used in the online environment. Then the processed code will be very different from the source code. When there is bug, we can only locate the compressed code, but not the code in the development environment. It is not easy for developers to locate the mode, so sourceMap appears to solve the problem of bad mode code.
The available values for SourceMap are as follows (the more + signs, the faster the speed, the more-signs, the slower the speed, and o represents medium speed)
1.png
Development environment recommendation: cheap-module-eval-source-map
Production environment recommendation: cheap-module-source-map
The reasons are as follows:
Cheap: the column information in the source code has no effect, so our packaged file does not want to contain column-related information, only row information can establish dependencies before and after packaging. So whether it's a development environment or a production environment, we want to add the basic types of cheap to ignore the column information before and after packaging.
Module: whether it is a development environment or a formal environment, we all want to locate the specific location of the source code of bug. For example, if an Vue file is reported to be incorrect, we want to locate a specific Vue file, so we also need to configure module.
Soure-map: source-map generates a separate soucemap file for each packaged module, so we need to add the source-map attribute
The eval-source-map:eval packaging code is very fast because it does not generate map files, but eval-source-map can be used in combination with eval to store the map file in the packaged js file as DataURL. Do not use eval-source-map in a formal environment because it increases file size, but in a development environment, you can try it because they are packaged quickly.
2.7. Output analysis of construction results.
The readability of the code output from Webpack is very poor and the file is very large, which gives us a big headache. In order to analyze the output more simply and intuitively, many visual analysis tools have emerged in the community. These tools show the results more visually in a graphical way, allowing us to quickly understand what the problem is. Let's talk about the analysis tool we used in the Vue project: webpack-bundle-analyzer.
We configure webpack.prod.conf.js in the project:
If (config.build.bundleAnalyzerReport) {var BundleAnalyzerPlugin = require ('webpack-bundle-analyzer'). BundleAnalyzerPlugin; webpackConfig.plugins.push (new BundleAnalyzerPlugin ());} copy code
After executing $npm run build\-- report, the analysis report is generated as follows:
1.png
2.8.Compiler optimization of Vue project
If your Vue project is compiled using Webpack and requires a cup of coffee, you may need to optimize the project's Webpack configuration to improve Webpack build efficiency. For details on how to optimize the Webpack construction of Vue projects, you can refer to another article by the author, "Webpack Optimization practice of Vue projects".
III. Optimization of basic Web technology
3.1enable gzip compression
Gzip is an acronym for GNUzip and was originally used for file compression in UNIX systems. Gzip encoding on the HTTP protocol is a technology used to improve the performance of web applications. Web servers and clients (browsers) must jointly support gzip. At present, mainstream browsers, Chrome,firefox,IE and so on all support this protocol. Common servers such as Apache,Nginx,IIS also support it. Gzip compression efficiency is very high, usually reaching 70% compression ratio, that is, if your web page has 30K, it becomes about 9K after compression.
Let's take the server using the familiar express as an example. Enabling gzip is very simple, and the relevant steps are as follows:
Installation:
Npm install compression-- save copy code
Add code logic:
Var compression = require ('compression'); var app = express (); app.use (compression ()) copy the code
Restart the service and observe the response header in the network panel. If you see the following fields in the red circle, the gzip is enabled successfully:
1.png
3.2. Browser cache
In order to improve the speed of users loading pages, it is very necessary to cache static resources. According to whether it is necessary to re-initiate a request to the server to classify HTTP caching rules, HTTP caching rules are divided into two categories (mandatory caching and comparison caching). If the caching mechanism is not clearly understood, you can refer to the author's article on HTTP caching "in-depth understanding of HTTP caching mechanisms and principles", which will not be discussed here.
3.3.The use of CDN
Browsers have to connect to the server when downloading files such as CSS, js and pictures from the server, but most servers have limited bandwidth. If the limit is exceeded, the web page will be unable to respond for half a day. CDN can load files through different domain names, which greatly increases the number of concurrent connections to downloaded files, and CDN has better availability, lower network delay and packet loss rate.
3.4. use Chrome Performance to find performance bottlenecks
Chrome's Performance panel can record js execution details and time over a period of time. The steps to analyze page performance using Chrome developer tools are as follows.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Open the Chrome developer tool and switch to the Performance panel
Click Record to start recording
Refresh the page or expand a node
Click Stop to stop recording
At this point, I believe that everyone on the "Vue project performance optimization method tutorial" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.