How to make code run faster? Vue performance speedup guide

How to make code run faster? Vue performance speedup guide

Preface

In the Internet era, users' expectations for web pages are like high-speed trains, and everything needs to be completed in an instant. As front-end engineers, one of our tasks is to ensure that the page loads quickly enough so that users do not feel the wait. This article will open the magic door to Vue performance optimization for you, and let us embark on a journey of speed improvement together.
Insert image description here

Reduce HTTP requests

Reducing HTTP requests is a key strategy for optimizing web page performance. HTTP requests are one of the overheads incurred by the browser when loading web pages, so reducing the number of requests can significantly improve page loading speed. Here are some ways to reduce HTTP requests:

  1. Merge files: Merge multiple CSS files or JavaScript files into one file, reducing the number of files and thereby reducing the number of HTTP requests. This can be achieved through build tools (such as Webpack) or server-side configuration.

  2. Sprites (CSS Sprites): Merge multiple small icons into one large image, and display different icons through the CSS background-position property. This reduces the number of HTTP requests for image files.

  3. Image lazy loading: For images on the page, you can use lazy loading technology. Only load images when they enter the user's visible area, rather than loading all images at the beginning. This can be achieved by setting the loading="lazy" attribute or using JavaScript.

    <img src="placeholder.jpg" data-src="image-to-lazy-load.jpg" alt="Lazy Loaded Image" loading="lazy">
    
  4. Use CSS icon fonts: You can use CSS icon fonts instead of image icons. Font files are typically smaller than image files, and the entire font can be loaded with a single HTTP request.

  5. Use CSS and JavaScript resource compression: In a production environment, use tools to compress CSS and JavaScript files to reduce file size, thereby reducing the transmission time of HTTP requests.

  6. Use browser caching: Set appropriate cache headers so that the browser can cache static resources. In this way, when the user visits the website again, the HTTP requests to the server can be reduced.

  7. Lazy loading of JavaScript: Delay loading of JavaScript code that does not need to be executed immediately, and only load and execute it when needed. This can be achieved by adding the async or defer attribute to the <script> tag.

    <script async src="your-script.js"></script>
    
  8. Use CDN: Use a content distribution network (CDN) to provide static resources, which can speed up the loading speed of resources and reduce the delay of HTTP requests.

  9. Utilize LocalStorage: For some small, infrequently changing data, you can consider storing it in LocalStorage to reduce requests to the server.

  10. Reduce redirects: Reduce the number of redirects in the page, as each redirect adds an additional HTTP request.

  11. Use font icons: Use a font icon library such as Font Awesome to reduce HTTP requests for small icons.

When making these optimizations, there are trade-offs between file size, load time, and user experience. Sometimes the merging of certain files can lead to increased load times, so when implementing these optimizations it's best to evaluate them using a performance testing tool like Google PageSpeed ​​Insights or Lighthouse.

Asynchronous loading

Asynchronous loading is a technique for loading resources or executing code without blocking page loading. Through asynchronous loading, the performance and user experience of the page can be improved. Here are some common asynchronous loading techniques:

  1. Load JavaScript asynchronously:

    • Use the attribute of the <script> tag so that the JavaScript file will not block the rendering of the page when downloading and will be executed asynchronously after the download is completed. async

      <script async src="your-script.js"></script>
      
    • Use the attribute of the <script> tag to defer execution of the JavaScript file until the document is parsed. Unlike , guarantees that scripts are executed in the order they appear in the document. deferasyncdefer

      <script defer src="your-script.js"></script>
      
    • Asynchronously load JavaScript files programmatically by dynamically creating<script> elements.

      var script = document.createElement('script');
      script.src = 'your-script.js';
      document.head.appendChild(script);
      
  2. Load CSS asynchronously:

    • Use<link> tag's rel attribute set to "stylesheet" and as Property is set to "style" so that the CSS file will be loaded asynchronously.

      <link rel="stylesheet" href="your-style.css" as="style" onload="this.rel='stylesheet'">
      
    • Dynamically created<link> elements via JavaScript to load CSS files asynchronously.

      var link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'your-style.css';
      document.head.appendChild(link);
      
  3. Load images asynchronously:

    • Use<img> tag and set the loading attribute to "lazy" so that when the image enters the user's visible area Just loaded.

      <img src="your-image.jpg" alt="Your Image" loading="lazy">
      
    • Dynamically created<img> elements via JavaScript to programmatically load images asynchronously.

      var img = new Image();
      img.src = 'your-image.jpg';
      document.body.appendChild(img);
      
  4. use asyncsum await:

    • Use the async and await keywords in JavaScript to execute functions or load resources asynchronously.

      async function fetchData() {
              
              
        const response = await fetch('your-data.json');
        const data = await response.json();
        // 处理数据
      }
      
      fetchData();
      

Asynchronous loading is suitable for resources or code that do not affect the first rendering of the page, but need to be executed after the page is loaded. When using asynchronous loading, you need to pay attention to the loading order and dependencies of resources to ensure the normal operation of page functions.

Lazy loading of components

Component lazy loading is a technique for optimizing front-end performance. It allows the application to be divided into smaller code blocks and loaded on demand, thereby reducing initial load time. Modern front-end frameworks, such as Vue, React, and Angular, all provide mechanisms for lazy loading of components.

Lazy loading of components in Vue:

In Vue, you can use Dynamic Import and Webpack's Code Splitting to implement lazy loading of components. Here is a simple example:

// 在路由配置中使用懒加载
const Foo = () => import('./Foo.vue');
const Bar = () => import('./Bar.vue');

const routes = [
  {
    
     path: '/foo', component: Foo },
  {
    
     path: '/bar', component: Bar }
];

In the above example, import statement returns a Promise. Vue Router will automatically parse this Promise when needed and load the corresponding component. This way, the relevant components will be downloaded and rendered only when the user accesses the /foo or /bar route.

Lazy loading of components in React:

In React, you can use the React.lazy() function and the Suspense component to implement lazy loading of components. Here is a simple example:

// 使用 React.lazy 定义懒加载组件
const Foo = React.lazy(() => import('./Foo'));
const Bar = React.lazy(() => import('./Bar'));

// 使用 Suspense 包裹懒加载组件
function App() {
    
    
  return (
    <div>
      <Suspense fallback={
    
    <div>Loading...</div>}>
        <Foo />
        <Bar />
      </Suspense>
    </div>
  );
}

In the above example, React.lazy(() => import('./Foo')) returns a lazy loading component, and the <Suspense> component is used to display a loading interface when loading the lazy loading component.

Lazy loading of components in Angular:

In Angular, you can use the loadChildren attribute in Angular routing configuration to implement lazy loading of components. Here's a simple example:

// 在路由配置中使用懒加载
const routes: Routes = [
  {
    
     path: 'foo', loadChildren: () => import('./foo/foo.module').then(m => m.FooModule) },
  {
    
     path: 'bar', loadChildren: () => import('./bar/bar.module').then(m => m.BarModule) }
];

In the above example, the value of the loadChildren attribute is a function that returns a lazy-loaded module. When a user accesses the /foo or /bar route, the corresponding module is downloaded and rendered.

Summarize:

Lazy loading of components is an important means to optimize front-end performance. By loading components on demand, the initial loading time can be reduced and the user experience improved. Different front-end frameworks have different implementation methods, but the core idea is to divide the application into smaller code blocks and load them on demand.

Advantages of Virtual DOM

Virtual DOM (Virtual DOM) is a commonly used optimization method in front-end development, mainly used in React and some other modern JavaScript frameworks. The advantages of virtual DOM are reflected in the following aspects:

  1. Performance optimization:

    • Reduce redrawing and reflow: Virtual DOM maintains a lightweight DOM tree structure in memory, and compares the difference between the two virtual DOMs before and after (called "reconcile" or "diff"), find the smallest changes, and then update the actual DOM in batches, thus reducing browser redraws and reflows.
    • Asynchronous updates: Some front-end frameworks use virtual DOM to implement batch asynchronous updates, that is, multiple state changes are merged into one, and then the changes are applied in the next event loop, reducing duplication. DOM operations to improve performance.
  2. Cross-platform development:

    • The design concept of virtual DOM can make front-end code easier to implement cross-platform development. For example, frameworks such as React Native use virtual DOM to render similar UI on different platforms.
  3. Simplify the complexity:

    • Virtual DOM can shield the complexity of underlying DOM operations, allowing developers to focus more on application logic rather than manually managing the state of the DOM. This can reduce the difficulty of code maintenance and improve development efficiency.
  4. Better development experience:

    • Through virtual DOM, developers can operate DOM more flexibly without having to deal directly with the underlying DOM API, thus improving development efficiency and code maintainability.
    • Developers can adopt a declarative programming style to make the code more readable and maintainable by describing the target state instead of manually manipulating the DOM.
  5. Component development:

    • Virtual DOM promotes the practice of component development. Each component can maintain its own virtual DOM tree, and by combining the virtual DOM of these components, the UI of the entire application can be built. This makes component development, testing, and maintenance easier.
  6. Rich ecosystem:

    • Due to the popularity of virtual DOM, many related tools and libraries have emerged, such as hot updates, time-travel debugging, etc., making the front-end development ecosystem richer.

Overall, virtual DOM has significant advantages in improving performance, simplifying development complexity, and enabling cross-platform development, and has become one of the important features of modern front-end frameworks.

Use cache wisely

Reasonable use of cache is an important strategy for front-end performance optimization, which can significantly improve web page loading speed and user experience. Here are some guidelines and best practices for using caching appropriately:

1. Browser caching mechanism:

  • Take advantage of the browser caching mechanism by setting the appropriate Cache-Control and Expires (or max-age) headers to control The cache time of the resource. This reduces requests to the server and speeds up page loading.

2. Fingerprinting:

  • Includes a hash of the file's contents as a fingerprint in the file name, for example, main-abc123.js. In this way, when the file content changes, the file name will change, forcing the browser to re-download the file to ensure that the user gets the latest version.

3. Version copy:

  • Embed the resource's version number into a file path or query parameter, for example, main?v=123. Update the version number each time to ensure that the browser obtains the latest resources.

4. Server-side cache:

  • Using server-side caching, for example, utilizing HTTP cache headers (Last-Modified and ETag), the server can return a 304 status for resources that do not change frequently code, indicating that the resource has not been modified, thereby reducing the amount of data transmission.

5. LocalStorage 和 SessionStorage:

  • UseLocalStorage and SessionStorage to store some data that does not change much for users, such as user configuration items, user identity tokens, etc., to avoid Request from server every time.

6. CDN Posted:

  • Use content distribution network (CDN) to cache static resources, reduce resource loading time, and improve global access speed.

7. Dynamic data cache:

  • For dynamic data, use an appropriate caching strategy, for example, use Service Worker or IndexedDB on the front end and cache middleware on the back end. For frequently changing data, a caching mechanism that is effective within a certain period of time can be used.

8. HTTP service:

  • Set appropriate HTTP cache headers, includingCache-Control, Expires, Last-Modified, ETagWait. This tells the browser when it needs to re-request the resource.

9. Resource preloading and preparsing:

  • Use the attribute of the <link> tag and the attribute of the tag to Load key resources in advance to reduce page loading delays. preload<meta>dns-prefetch

10. Removal:

  • Use offline caching technology, such asService Worker, so that applications can still access cached resources when offline.

11. Cache cleaning strategy:

  • Consider triggering cache cleanup when resources are updated to ensure that users always get the latest resources. Cache cleaning can be achieved using version numbers, fingerprints, etc.

12. 压缩和合并:

  • Use compression and merging technology to merge multiple small files into one large file, reduce the number of requests, and reduce file size through compression to increase loading speed.

Reasonable use of caching requires comprehensive consideration of static resources, dynamic data, user experience and other factors based on specific business scenarios and needs, and using a combination of multiple caching strategies to achieve the best results. At the same time, the caching strategy is regularly evaluated and adjusted to ensure that it adapts to system evolution and changes.

Image optimization

Image optimization is one of the key steps in web page performance optimization. It can reduce page loading time, improve user experience, and reduce the demand for server bandwidth. Here are some common image optimization techniques and best practices:

1. Choose an appropriate image format:

  • JPEG: Suitable for photos and images, supports high compression ratios, but does not support transparency.
  • PNG: Suitable for icons, logos and other images that require transparency, but the file size is larger.
  • GIF: Suitable for simple animations, supports transparency, but has a limited number of colors.
  • WebP: A high-performance image format launched by Google that supports high compression ratio and transparency, but browser support is limited.

2. 压缩图片:

  • Use compression tools (such as TinyPNG, ImageOptim) to perform lossless or lossy compression on images to reduce file size, ensure image quality, and improve loading speed.

3. Use appropriate resolution:

  • Avoid displaying images on your webpage that are larger than necessary. Provide images at multiple resolutions depending on the display device and screen size, and use the <picture> or srcset attributes to select the appropriate image based on the screen size.
<img srcset="image-1x.jpg 1x, image-2x.jpg 2x, image-3x.jpg 3x" alt="Responsive Image">

4. Lazy Loading:

  • Use lazy loading technology to delay the loading time of images and only load them when they enter the user's viewport. This can be achieved via the loading="lazy" attribute or JavaScript.
<img src="placeholder.jpg" data-src="image-to-lazy-load.jpg" alt="Lazy Loaded Image" loading="lazy">

5. CSS used:

  • For small icons and UI elements, consider using a CSS icon font or icon collection (like Font Awesome) instead of loading them as images.

6. Snow Green (CSS Sprites):

  • Merge multiple small icons into one large image, and display different icons through the CSS background-position attribute. This reduces multiple requests and improves performance.

7. Gantai-style encyclopedia:

  • Use responsive images to ensure they look good across devices and screen sizes. This can be achieved using the <picture> element or the srcset attribute.

8. Resistance:

  • Ensure that the browser can cache images and reduce repeated downloads by setting appropriate cache headers (Cache-Control and Expires).

9. Image optimization tools:

  • Use image optimization tools, such as OptiPNG, JPEGoptim, SVGO, etc., to automatically optimize image files and reduce file size.

10. CDN used:

  • Host images to a content delivery network (CDN) to serve images from servers closer to users, reducing loading times.

11. Kaiyo present case style:

  • For modern browsers, consider using modern image formats like WebP for better compression.

12. Preloading:

  • For images that will be used on the page, you can use <link> tagsrel="preload" to preload and obtain resources in advance.
<link rel="preload" href="image-to-preload.jpg" as="image">

By combining these image optimization technologies, you can improve web page loading speed and user experience while ensuring image quality.

code splitting

Code Splitting is a front-end performance optimization technique that aims to divide the application code into smaller, independently loadable code blocks. This helps reduce initial load times and improves app performance. Here are some common code splitting techniques and practices:

1. Dynamic Import:

  • In environments that support dynamic imports, you can use the dynamicimport() syntax to load modules asynchronously.
// 之前
import Module from './module';

// 动态导入
const modulePromise = import('./module');

modulePromise.then(module => {
    
    
  // 使用模块
});

2. Lazy loading in React (React.lazy):

  • React provides theReact.lazy() function to implement component-level lazy loading. Lazy-loaded components will not be loaded during the initial rendering, and will only be loaded asynchronously when the component is actually needed.
const MyComponent = React.lazy(() => import('./MyComponent'));

// 使用 <Suspense> 包裹,显示加载中的提示
<Suspense fallback={
    
    <div>Loading...</div>}>
  <MyComponent />
</Suspense>

3. Vue 中的懒加载:

  • Vue also supports component-level lazy loading. You can use the factory function to return a Promise that is called by import().
const MyComponent = () => import('./MyComponent.vue');

// 在路由中使用
const routes = [
  {
    
     path: '/my-component', component: MyComponent }
];

4. Webpack’s code splitting:

  • Webpack is a popular packaging tool that supports code splitting through import() syntax and special comment syntax.
// 使用 import() 进行代码分割
const modulePromise = import('./module');

// 使用注释进行代码分割
import(/* webpackChunkName: "my-chunk" */ './module').then(module => {
    
    
  // 使用模块
});

5. Vue Router's description:

  • In Vue Router, you can use the factory function to return the Promise called byimport() to implement lazy loading at the routing level.
const MyComponent = () => import('./MyComponent.vue');

const routes = [
  {
    
     path: '/my-component', component: MyComponent }
];

6. Lazy loading at routing level:

  • Divide the application's routes into multiple modules, and only load the corresponding modules according to the routes accessed by the user, thereby reducing the initial loading time.

7. Additional demand:

  • For some large third-party libraries, you can load only part of the code needed in the application through on-demand loading, reducing the overall file size.

8. Prefetching and Preloading:

  • Use <link> tags rel="prefetch" and rel="preload" to load resources that may be needed in advance when idle.
<!-- 预取 -->
<link rel="prefetch" href="module.js" as="script">

<!-- 预加载 -->
<link rel="preload" href="module.js" as="script">

9. Service Worker caching strategy:

  • Use Service Workers to cache and serve parts of your application offline to further optimize the user experience.

Code splitting allows apps to load code on demand, improving loading performance and reducing initial app load times. Choosing the appropriate code splitting technique depends on the needs of the application and the front-end framework being used.

Performance monitoring and tuning

Performance monitoring and tuning is a vital part of front-end development, which involves identifying and solving application performance bottlenecks to provide a better user experience. Here are some key aspects of performance monitoring and tuning:

1. Performance monitoring tools:

  • Use browser developer tools (DevTools) to monitor web page performance. The browser provides some performance analysis tools, such as Performance and Network panels, which can view page loading time, resource loading time, JavaScript execution time, etc.
  • Use performance monitoring tools, such as Lighthouse, Google PageSpeed ​​Insights, WebPageTest, etc. These tools can provide detailed performance analysis reports and give optimization suggestions.

2. User experience monitoring:

  • Use user experience monitoring tools, such as Google Analytics, New Relic, etc., to collect data about user experience. This includes metrics such as page load times, interaction times, error rates, and more to help understand the actual user experience when using your app.

3. Front-end performance indicators:

  • Pay attention to core front-end performance indicators, including:
    • First Contentful Paint (FCP): The time when the first piece of content on the page starts to be drawn.
    • First Meaningful Paint (FMP): The first time meaningful content appears on the page.
    • Time to Interactive (TTI): The time the page becomes interactive.
    • Total Blocking Time (TBT): Total time to block user input.
    • Cumulative Layout Shift (CLS): The cumulative fraction of layout changes caused by unstable elements on the page.

4. JavaScript performance improvement:

  • Reduce JavaScript file size, compress and obfuscate code to reduce download times.
  • Use lazy loading and code splitting to only load necessary JavaScript when needed.
  • Avoid unnecessary double calculations and use caching and optimization algorithms.
  • Use theasync and defer properties to load and delay script execution asynchronously.

5. Network request optimization:

  • Use a CDN (Content Delivery Network) to speed up resource loading and reduce request latency.
  • Compress and merge static files to reduce file size.
  • Use resource caching to reduce duplicate downloads by setting appropriate cache headers.

6. Image and multimedia optimization:

  • Choose an appropriate image format and compress images to reduce file size.
  • Use lazy loading technology to only load images when they enter the user's viewport.
  • Avoid large, unnecessary multimedia files.

7. DOM manipulation and rendering:

  • Avoid frequent DOM operations and use batch operations whenever possible.
  • Use virtual DOM technology to reduce the cost of DOM updates.
  • Avoid expensive operations during layout and drawing phases.

8. Transition end improvement:

  • Optimize the mobile viewport and layout to ensure good display on small screens.
  • Use appropriate media queries and responsive design.
  • Avoid using too many mobile-specific JavaScript libraries and frameworks.

9. Server-side performance optimization:

  • Optimize server response time, use caching and asynchronous processing.
  • Enable compression algorithms to reduce the amount of data transferred.
  • Use load balancing and caching strategies to improve server processing capabilities.

10. Monitoring and continuous optimization:

  • Set up performance monitoring, regularly check application performance, and perform continuous optimization based on monitoring data.
  • Use error monitoring tools to track and resolve errors in your application to ensure users are not affected.
  • Conduct A/B testing to compare the effects of different optimization strategies and choose the best solution.

By comprehensively considering the above aspects, developers can comprehensively improve the performance of front-end applications and provide a better user experience.

Best practices and tool recommendations

The following are some best practices in front-end development and some commonly used tool recommendations, which cover aspects such as performance optimization, code quality, development workflow and team collaboration:

Best Practices:

  1. Code version control:

    • Use a version control system, such as Git, to manage code versions and changes.
  2. Code specifications:

    • Following consistent code styles and specifications, you can use tools such as ESLint (JavaScript), stylelint (CSS), etc. to perform static code analysis.
  3. Modular development:

    • Use modular development and adopt a modular code organization method, such as the ES6 module system.
  4. Performance optimization:

    • Optimize front-end performance, including compressing and merging files, reducing image and multimedia file size, lazy loading and code splitting, etc.
  5. Responsive design:

    • Use responsive design to ensure a good user experience on different devices.
  6. safety:

    • Implement security best practices, including preventing cross-site scripting attacks (XSS), cross-site request forgery (CSRF), and more.
  7. Error monitoring:

    • Use error monitoring tools, such as Sentry and Bugsnag, to monitor and track errors in applications in real time.
  8. test:

    • Write unit tests and integration tests using tools such as Jest (JavaScript), React Testing Library, Cypress, etc.
  9. Build tools:

    • Use modern build tools such as Webpack and Parcel to optimize code, resources and packaging.
  10. Performance monitoring and analysis:

    • Use tools such as Lighthouse and Google PageSpeed ​​Insights to perform performance analysis on the website.

Tool recommendations:

  1. Editor/IDE:

  2. version control:

  3. Code quality:

    • ESLint - JavaScript code specification and static analysis tool.
    • stylelint - CSS code specification and static analysis tool.
    • Prettier - Code formatting tool.
  4. Build tools:

  5. Package manager:

  6. test:

  7. Performance optimization:

  8. Error monitoring:

    • Sentry - Open source bug tracking tool.
    • Bugsnag - Real-time bug monitoring and reporting tool.
  9. Collaboration and communication:

  10. Task management:

These tools and best practices help improve development productivity, code quality, and application performance while promoting team collaboration and communication. These tools can be flexibly selected and configured based on project needs and team preferences.

Guess you like

Origin blog.csdn.net/m0_68390957/article/details/134494373