Performance optimization in Vue projects

Performance optimization in Vue projects

1. Coding stage

  • Minimize the data in data, the data in data will add getter and setter, and will collect the corresponding watcher

  • v-if and v-for distinguish usage scenarios, v-if and v-for should not be used together;

  • v-for traversal must add a key to the item, the key guarantees uniqueness, and avoid using vif at the same time

  • Computed and method distinguish usage scenarios

  • Lazy loading of routes, lazy loading of pictures, dynamic loading of long lists

  • Import third-party modules on demand

  • Use anti-shake, throttling functions for short mass operations (zooming, scrolling)

  • event destruction

  • SPA pages use keep-alive caching components

  • Delayed loading of components can divide page resources into multiple parts, which will be loaded on demand when they are used, thus reducing the consumption of the first loading.

  • The code is simplified, the console is removed, and the reusable methods and components are extracted

  • Do not write inline styles to avoid dom redrawing

2. SEO optimization

  • Server-Side Rendering SSR
  • pre-rendered

3. Package optimization

  • compressed code
  • Tree Shaking/Scope Hoisting
  • Use CDN to load third-party modules
  • Multi-threaded packaging happypack
  • splitChunks extract common files
  • sourceMap optimization

Performance optimization in Vue projects

1. Optimization at the code level

  • v-if and v-show distinguish usage scenarios

  • Computed and watch differentiate usage scenarios

  • v-for traversal must add key to item, and avoid using v-if at the same time

  • Long list performance optimization, if the list is purely for data display, there will be no change, Object.freeze(), virtual scrollingvue-virtual-sroller

  • Reduce redraws and reflows

  • event destruction

  • Image lazy loadingvue-lazyload

  • Routing lazy loading

  • On-demand introduction of third-party plug-ins

  • Appropriate use of keep-alive cache

  • Anti-shake, throttling application

  • html, css, js optimization

2. Optimization at the Webpack level

  • Small image to base64
  • Compressing images (image-webpack-loader)
  • Reduce redundant code from ES6 to ES5
  • splitChunks extract common files
  • Template precompilation
  • Optimize SourceMap
  • Build result output analysis: webpack-bundle-analyzer
  • Compilation optimization for Vue projects

3. Optimization of basic web technologies

  • Accept-EncodingEnable gzip compression: Web clients can identify support for compression through the header in the HTTP request
  • Browser cache (strong cache, negotiation cache)
  • Static resources use CDN (the main function of CDN is to cache content in different locations, and use load balancing technology to direct user requests to the most appropriate cache server to obtain content)
  • Reduce the number of HTTP requests
  • Minify JavaScript and CSS
  • Background distributed deployment, load balancing
  • Server-Side Rendering SSR
  • pre-renderedprerender-spa-plugin

4. Non-framework code optimization

  • Reduce redrawing, rearrangement
  • Put CSS at the top of the page and JavaScript at the bottom
  • Reduce DNS queries

HTML performance optimization

    1. HTML tags have always. Reduce browser judgment time
    1. Move the script tag to the end of the HTML file, because JS will block the display of subsequent pages.
    1. Reduce the use of iframe, because iframe will add an http request, prevent the page from loading, even if the content is empty, it will take time to load
    1. id and class, simplify the naming, use '-' instead of '_' for connection symbols in conjunctions containing keywords
    1. Keep a uniform case, which is beneficial to browser caching. Although browsers are not case-sensitive, the w3c standard is lowercase
    1. Clear spaces. Although spaces help us to view the code, each space is equivalent to a character. The more spaces, the larger the page size. The homepages of search engines such as google and baidu have removed all possible spaces, carriage returns, etc. characters, which can speed up the transmission of web pages. With the help of DW software, you can delete the spaces between tags in html in batches, ctrl+a in sublime text, and then long press shift+tab to left-align all, and clear the spaces at the beginning of the line
    1. Reduce unnecessary nesting and make it as flat as possible, because when the browser compiler encounters a tag, it will start looking for its end tag, and its content will not be displayed until it matches, so when there are many nested pages, the page will be opened Very slow.
    1. Reduce comments, because too many comments not only take up space, but if there are a lot of keywords in it, it will affect the search engine search
    1. Use css+div instead of table layout, remove formatting control tags such as: strong, b, i, etc., and use css control
  • 10. The code should be structured and semantic
  • 11. Try to separate css and javascript into separate files

css performance optimization

    1. More use of inheritance, styles common to multiple child elements, if the style can be inherited, write it on the parent element
    1. Minimize the number of redraws and rearrangements
    1. Selector naming convention, find faster by id
    1. Animate regions to enable separate layers
    • 1) Orientation: position: absolute/relative

    • 2) Will-change: xxx;

    1. Merge and compress your css files to reduce http requests, you can use tools or automated construction.
    1. Use CSS sprites for your images

JS performance optimization

  • \1. Combine and compress js
  • \2. Reduce operations on DOM, avoid redrawing and rearranging
  • \3. Reduce the number of requests and save network resources
  • \4. Encapsulate functional functions to achieve reuse
  • \5. Avoid defining variables in loop statements
  • \6. Use closures with caution
  • \7. Function throttling, function anti-shake

HTML performance optimization

  • \1. HTML tags have always. Reduce browser judgment time
  • \2. Move the script tag to the end of the HTML file, because JS will block the display of subsequent pages.
  • \3. Reduce the use of iframe, because iframe will add an http request to prevent the page from loading, even if the content is empty, it will take time to load
  • \4. id and class, on the basis of being able to understand, simplify the naming, use '-' instead of '_' for connection symbols in conjunctions containing keywords
  • \5. Keep a uniform case, which is conducive to browser caching. Although browsers are not case-sensitive, the w3c standard is lowercase
  • \6. Clear spaces. Although spaces help us to view the code, each space is equivalent to a character. The more spaces, the larger the page size. The homepages of search engines such as google and baidu have removed all spaces that can be removed. Carriage return and other characters, which can speed up the transmission of web pages. With the help of DW software, you can delete the spaces between tags in html in batches, ctrl+a in sublime text, and then long press shift+tab to left-align all, and clear the spaces at the beginning of the line
  • \7. Reduce unnecessary nesting and make it as flat as possible, because when the browser compiler encounters a tag, it will start looking for its end tag, and its content will not be displayed until it matches, so open when there are many nests The page will be extremely slow.
  • \8. Reduce comments, because too many comments not only take up space, but if there are a lot of keywords in it, it will affect the search engine search
  • \9. Use css+div instead of table layout, remove formatting control tags such as: strong, b, i, etc., and use css control
  • \10. The code should be structured and semantic
  • \11. Try to separate css and javascript into separate files

css performance optimization

  • \1. Make more use of inheritance, the common style of multiple child elements, if the style can be inherited, it will be written on the parent element

  • \2. Minimize the number of redraws and rearrangements

  • \3. Selector naming convention, find faster by id

  • \4. The animation area opens a separate layer

    • 1) Orientation: position: absolute/relative

    • 2) Will-change: xxx;

  • \5. Merge and compress your css files to reduce http requests, you can use tools or automated construction.

  • \6. Use CSS sprites to process your images

JS performance optimization

    1. Merge and compress js
    1. Reduce operations on DOM, avoid redrawing and rearranging
    1. Reduce the number of requests and save network resources
    1. Encapsulate functional functions to realize reuse
    1. Avoid defining variables in loop statements
    1. Use closures with caution
    1. Function throttling, function anti-shake

Front-end optimization

1. Load optimization (reduce the number of http requests)

  • Merge pictures : When there are many pictures, such as sprite pictures and sprite pictures, they can be combined into one large picture, thereby reducing the number of http requests. Pictures that change frequently may not be suitable, and pictures that change relatively stable can be considered. In addition to reducing the number of http requests, merging large images can also make full use of the cache to improve performance.
  • Merge and compress css style sheets and js scripts , their common purpose is to reduce the number of http connections.
  • UI library loaded on demand
  • Lazy loading of routing components
  • Remove unnecessary requests , develop and write codes or residual invalid request connections after system upgrades.
  • First screen loading : Fast display on the first screen can greatly improve the user's perception of page speed, and corresponding optimization should be made for the fast display on the first screen.
  • Make full use of cache : to reduce the number of requests sent to the server and save network resources, all static resources should be placed on the server side and cached, and long caches should be used as much as possible.
  • Preloading : Loading can be used for large resource pages, and the page will be displayed after the resources are loaded. However, if the loading time is too long, it will cause a negative experience.
  • Asynchronous loading of third-party resources : Third-party resources are uncontrollable and will affect page loading, so third-party resources must be loaded asynchronously.

2. Image optimization

  • Use images in PNG format as much as possible . It is relatively small in size and can be compressed with tools. It is best to optimize before going online.
  • Lazy loading of images Lazy loading of images
  • Avoid empty src attributes of tags such as img and iframe : empty src will reload the current page, affecting speed and efficiency.
  • Try to avoid using DataURL for images : DataURL images do not use image compression algorithms, the files will become larger, and they must be decoded before rendering, slow loading and time-consuming.

3. Use CDN

CDN: Realize the network system that distributes content from the central media server to the edge server, that is, the content distribution network. CDN has lower network delay and packet loss rate, can distribute load, save bandwidth and improve website performance, and enable users to get all the information nearby. Need content, solve the situation of network congestion, and improve the response speed of users visiting the website.

If security is important to your website, don't use a public CDN, because when you remotely request files from the CDN, your access source information is also sent, and some remote js files may be modified to collect your User or system information, and when you use the https protocol, the CDNs you can choose are even more limited.

4. Turn on Gzip (code compression)

Gzip is data compression. In the front-end production environment, files such as js, css, and pictures are compressed. By reducing the amount of data transmission, the transmission time is reduced, the server network bandwidth is saved, and the front-end performance is improved.

Compress time, process, description

img

5. Optimization of style sheets and JS files

  • The styles and scripts inline in the header will block the rendering of the page. Generally, we will put the css style sheet file in the head of the file and use the link to import it, so that the CSS style sheet can be downloaded as soon as possible.
  • Corresponding to the js script file, generally we put the script at the end and load it asynchronously, so as to minimize the blocking of styles and scripts on the page.

6. Reduce unnecessary cookies

Cookies are stored on the client side and are transmitted between the browser and the server along with HTTP requests. Since cookies are sent to the server through HTTP requests when accessing resources under the corresponding domain name, this will affect the loading speed, so try to reduce unnecessary cookies .

7. Script optimization

  1. For complex animation effects, use absolute positioning to keep it out of the document flow, avoid looping DOM elements, and use transform:translate instead of position left, right...to minimize reflow and redrawing.

  2. Move the script back to reduce the impact on concurrent downloads.

  3. Cache the value of .length: Each .length calculation uses a variable to hold the value.

  4. Try to use event delegation: do not set event listeners for each child node separately, but set it on its parent node, and then use the bubbling principle to set each child node to avoid batch binding events to reduce memory consumption and DOM operations.

  5. Try to use the id selector: the id selector is the fastest to select elements, and has the advantages of uniqueness, flexibility and priority.

8. Optimization of front-end code structure

  • Set Viewport : HTML viewport can speed up page rendering.

  • Reduce DOM node design: Too many DOM nodes will affect the rendering of the page.

  • Set as much as possible to use css3 animation design: Reasonably use requestAnimationFrame animation instead of setTimeout.

  • Set to optimize high-frequency events : Scroll, touchmove and other events should be limited by using functions such as anti-shake and throttling as much as possible.

  • Do not abuse WEB font design: WEB fonts need to be downloaded, parsed, and redraw the current page, and the use should be minimized.

  • File naming rules must be uniform and meaningful , and files of the same type are classified into the same folder.

Nine, SEO optimization

  • Title : The number of words in the title should not be too long. Generally, the core keywords and content related to the theme of the website should be written.
  • Description : The description is a comprehensive description of the entire page. Its function and importance are second only to the title. The description should be more attractive. It should include your company's brand name and phone number, and include target keywords.
  • Keywords : Optimizing keywords can allow users to accurately locate the content and website they want to search for when searching for keywords, and allow the website to be seen by more people in need.
  • Website code : The website code should be as streamlined as possible to save time for Baidu spiders, which is especially important for large websites.

Realize vue first screen loading optimization

  • Put the infrequently changed library in index.html and import it through cdn

  • Reduce the size of the entry file : route lazy loading

  • Local cache of static resources : Reasonable use of localStorage by the front end

  • UI framework loaded on demand

  • Compression of image resources : online font icons, sprite images

  • Use a lightweight tool library

  • Repeated packaging of components : Configuring CommonsChunkPlugin

    // 假设moment.js文件是一个常用的库,现在很多文件都使用了该文件,这就造成了重复加载
    // 解决方案: 在webpack的config文件中,修改CommonsChunkPlugin的配置。
    minChunks: 3 //把使用3次及以上的包抽离出来 放进公告依赖文件,避免了重复加载
    
  • Enable GZip compression : compression-webpack-plugin plugin

    nmp i compression-webpack-plugin -D //安装 compression-webpack-plugin 
    
    // 并在vue.config.js 中引入并修改webpack配置 在服务器上我们也要做相应的配置。
    const CompressionPlugin = require('compression-webpack-plugin') 
    configureWebpack: (config) => {
          
          
            if (process.env.NODE_ENV === 'production') {
          
          
                // 为生产环境修改配置...
                config.mode = 'production'
                return {
          
          
                    plugins: [new CompressionPlugin({
          
          
                        test: /\.js$|\.html$|\.css/, //匹配文件名
                        threshold: 10240, //对超过10k的数据进行压缩
                        deleteOriginalAssets: false //是否删除原文件
                    })]
                }
          }
    }
    
  • Use SSR (server-side rendering) : components or pages generate html strings through the server, and then send them to the browser (Vue recommends using nuxt.js) to achieve server-side rendering.

How to optimize DNS resolution?

The full name of DNS is Domain Name System, which is a domain name system, 域名and it is IP地址a distributed database that maps to and from each other.

The browser's first domain name DNS resolution lookup process for the website is as follows:

Browser Cache - System Cache - Router Cache - ISP DNS Cache - Recursive Search

1. Reduce the number of DNS request queries (front-end)

DNS query also consumes response time. If the content of the web page comes from different domains, it will take a certain amount of time for the client to resolve these domains for the first time. However, because the DNS query results will be cached in the local system and browser for a period of time, the DNS query is generally Only has an impact on the speed of the first visit

2. Perform DNS prefetch: DNS Prefetch (front end)

  • DNS-prefetch (DNS prefetch) is to try to resolve the domain name before requesting resources, which may be the file to be loaded later, or the link target that the user is trying to open. Domain name resolution and content loading are serial network operations, so this method can reduce user waiting time and improve user experience.

  • DNS-prefetch can help developers mask DNS resolution delays. The link element of HTML provides this function through the rel attribute value of dns-prefetch, and then refers to the domain name to be cross-domain in the href attribute.

    How to set up dns-prefetch?

    Set X-DNS_prefetch-Control: on|off

    on : Enable DNS pre-resolution. When the browser supports the feature of DNS pre-resolution, the browser will still perform pre-resolution even if this label is not applicable.
    off : Turn off DNS pre-resolution. This attribute is useful when the links on the page are not controlled by you or you don't want to direct data to these domains at all

3. Extend the DNS cache time (operation and maintenance)

The DNS query process consumes about 20 milliseconds. During the DNS query process, the browser will do nothing and remain blank. If there are many DNS queries, web page performance will be greatly affected, so DNS caching is required.

The cache mechanism of different browsers is different: the default cache time of IE for DNS records is 30 minutes, the default cache time of Firefox for DNS records is 1 minute, and the default cache time of Chrome for DNS records is 1 minute.

Long cache time: reduce repeated DNS lookups and save time.

Short cache time: detect server IP changes in time to ensure the correctness of access.

4. Use CDN to accelerate domain names (operation and maintenance)

Guess you like

Origin blog.csdn.net/qq_37831545/article/details/129393915