The performance optimization part of the front-end interview (7) 10 small knowledge points per day


Table of contents


Series Article Directory

The performance optimization part of the front-end interview (1) 10 small knowledge points per day

The performance optimization part of the front-end interview (2) 10 small knowledge points per day

The performance optimization part of the front-end interview (3) 10 small knowledge points per day

The performance optimization part of the front-end interview (4) 10 small knowledge points per day

The performance optimization part of the front-end interview (5) 10 small knowledge points per day

The performance optimization part of the front-end interview (6) 10 small knowledge points per day

The performance optimization part of the front-end interview (7) 10 small knowledge points per day

knowledge points

61. How to optimize the loading time and rendering time of the front-end application to reduce the white screen time and improve user satisfaction?

  1. Optimize resource loading:
  • Use proper resource compression and minification tools to reduce file size, including JavaScript, CSS and images.
  • Use CDN (Content Delivery Network) to distribute static resources and load resources from the nearest server to speed up loading.
  • Use caching strategies to enable browsers to reuse downloaded resources and reduce unnecessary network requests.
  1. Use asynchronous loading:
  • Load non-critical assets and scripts asynchronously to avoid blocking the main rendering thread.
  • Use lazy loading (Lazy Loading) to delay loading the content of the invisible area, and only load resources when the user scrolls to the area.
  1. Code splitting and on-demand loading:
  • Divide the code into smaller modules and load them on demand to avoid loading unnecessary code.
  • Use Dynamic Import to load modules on demand to improve initial loading speed.
  1. Avoid rendering blocking:
  • Put JavaScript at the bottom of the page to avoid blocking the initial render.
  • Use asyncand deferattributes to asynchronously load and execute scripts without blocking DOM parsing.
  1. Choice of front-end framework and library:
  • Choose a lightweight framework or library to avoid unnecessary performance overhead.
  • Avoid loading too much framework code on initial load, but load it on-demand as needed.
  1. Image optimization:
  • Use an appropriate image format, such as WebP, to reduce image file size.
  • Use responsive images to load images at the appropriate size for different devices and screen sizes.
  1. CSS optimization:
  • Use inline CSS and media queries to avoid unnecessary external CSS requests.
  • Avoid using too many CSS styles and selectors to reduce the complexity of rendering.
  1. Server-Side Rendering (SSR):
  • For critical pages, use server-side rendering to generate HTML on the server side, reducing client-side rendering time.
  1. Front-end error monitoring and performance analysis:
  • Use front-end error monitoring tools to detect and resolve front-end errors in a timely manner.
  • Use performance analysis tools to monitor and identify performance bottlenecks for optimization.
  1. Performance testing and optimization:
  • Run performance tests regularly, simulating different network conditions and devices to evaluate and improve load and render times.

Using the above methods comprehensively can significantly reduce the loading time and rendering time of the front-end application, thereby reducing the white screen time and improving user satisfaction. Different projects may need to choose the appropriate optimization strategy according to the specific situation.

62. When building a Single Page Application (SPA), how do you handle routing lazy loading and code splitting to improve initial load speed?

Routing lazy loading and code splitting are very useful techniques when building a Single Page Application (SPA) that can help improve initial load speed. The combination of these two technologies can load the required code on demand when the user visits different pages, reducing the initial loading file size, thereby accelerating the loading speed of the application. Here are the general steps to handle route lazy loading and code splitting:

  1. Lazy routing with routing:
    Lazy routing is a technique for loading routing components on demand. It makes it so that only when a user visits a particular route does the code required for that route be loaded. This way, the code for not all routes is loaded on initial load, reducing the initial bundle size.

In Vue.js, you can use importfunctions combined with dynamic importsyntax to implement lazy loading of routes. The sample code is as follows:

const Home = () => import('./views/Home.vue');
const About = () => import('./views/About.vue');
const Contact = () => import('./views/Contact.vue');

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  { path: '/contact', component: Contact }
];

const router = new VueRouter({
  routes
});

In React, you can use React lazyfunctions to implement lazy loading of routes. The sample code is as follows:

import React, { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const Home = lazy(() => import('./views/Home'));
const About = lazy(() => import('./views/About'));
const Contact = lazy(() => import('./views/Contact'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/about" component={About} />
          <Route path="/contact" component={Contact} />
        </Switch>
      </Suspense>
    </Router>
  );
}

export default App;

  1. Code splitting and on-demand loading:
    In addition to routing lazy loading, you can further split the code and load other non-routing related modules and components on demand. This can be achieved through the code-splitting feature of bundling tools like Webpack. Split the functional modules in your app into smaller modules and load them on demand when needed. This reduces the bundle size on initial load and speeds up the loading of your app.
// 示例:Webpack中的代码拆分
import(/* webpackChunkName: "utils" */ './utils').then((utils) => {
  // 使用utils模块
});

The combined use of route lazy loading and code splitting can significantly improve the initial loading speed of single-page applications and provide users with a better experience. In practical applications, these technologies can be flexibly used to optimize application performance according to the structure and requirements of the project.

63. Ever tried using the WebP image format to reduce image loading time? Please share your application experience in actual projects.

WebP is a modern image format that is often more efficient than traditional JPEG and PNG formats, and can significantly reduce image file size, resulting in faster load times and improved page performance. Here are some suggestions for using the WebP image format in real projects:

  1. Browser Compatibility: Before using the WebP format, make sure that the browsers primarily used by your target audience support the WebP format. Most modern browsers support WebP, but there are still some older browsers that may not.
  2. Image Format Conversion: Convert existing JPEG or PNG images to WebP format. You can use an image editing tool such as Photoshop, GIMP, or an online tool to do the format conversion.
  3. Automated tools: Use plugins or tasks for build tools (eg Webpack, Gulp) to automatically convert images to WebP format and provide appropriate fallback images based on browser support.
  4. Responsive images: Serve appropriately sized WebP images for different screen sizes and devices to ensure good display on various devices.
  5. Server Configuration: Configure your server to serve WebP images correctly. You can use server configuration to detect whether a browser supports WebP, and serve images in the appropriate format accordingly.
  6. Detection and fallback: When using WebP images, ensure that appropriate fallback images are served on browsers that do not support WebP to ensure that all users can view the image content normally.
  7. Performance testing: After deploying WebP images, perform performance testing and analysis on a regular basis to ensure image loading times are improved and to optimize parts that require further tuning.

Overall, using the WebP image format can be an effective way to reduce image load times and improve page performance. But before applying it, it is important to carefully consider browser compatibility and implementation details to ensure the best user experience.

64. Do you think front-end performance optimization is a continuous process or a one-off task? Please explain your point of view and talk about how continuous improvement of performance optimization is driven in the team.

Front-end performance optimization is an ongoing process, not just a one-off task. This is because front-end performance optimization involves multiple factors, including the continuous evolution of technology, changes in projects, and changes in user behavior. Continuous optimization can ensure that front-end applications can maintain good performance in different situations, and can also adapt to changing environments.

Here are some reasons why front-end performance optimization is an ongoing process:

  1. Technology evolution: Front-end technologies and standards are constantly evolving, and new optimization methods and tools are constantly emerging. Continuous optimization ensures that you take advantage of the latest technologies and best practices to improve performance.
  2. Project changes: The requirements and functions of the project may change over time. The addition of new functions and the modification of old functions may affect performance. Continuous optimization ensures that new code changes do not negatively impact performance.
  3. Changes in user behavior: User behavior and usage habits may change over time, and traffic patterns may vary in different time periods and regions. Continuous optimization can be adjusted according to the actual usage of users to provide a better user experience.
  4. Performance Monitoring and Analysis: Continuous monitoring and analysis of application performance data can help you identify potential performance issues and take timely action to resolve them.

Driving continuous improvement in performance optimization across teams can take the following approaches:

  1. Set performance goals: Set clear performance goals at the beginning of the project, such as loading time, response time, etc., as a common goal of the team.
  2. Integrate performance optimization process: Incorporate performance optimization into the development process, for example, check for performance issues during code review, perform regular performance testing, etc.
  3. Knowledge sharing and training: Regularly organize knowledge sharing meetings and training courses to pass on the best practices and tools of performance optimization to team members.
  4. Tools and automation: Use performance monitoring tools and automation tools to help teams identify performance issues and conduct continuous monitoring and testing.
  5. Periodic review and improvement: After the project cycle ends, regularly review the effect of performance optimization, summarize lessons learned, and formulate improvement plans.
  6. Cross-Functional Collaboration: Work closely with design, backend, and operations teams to optimize overall performance and ensure that every link can perform at its best.

In general, continuous front-end performance optimization is a dynamic process that requires the joint efforts of the team and continuous improvement to ensure that the application always maintains high performance and a good user experience.

65. When using the front-end framework, how to avoid over-rendering (Over-Rendering) and unnecessary data requests to improve performance?

  1. Use conditional rendering: Before rendering a component or content, use a conditional statement to check whether it needs to be rendered. This avoids rendering unnecessarily.

  2. Component optimization: When writing components, avoid recalculating and processing the same data every render. Use shouldComponentUpdate(in React) or a similar mechanism to control whether rendering needs to happen.

  3. Virtualization technology: Use virtualization technology, such as React's virtual list (Virtualized List), to perform efficient rendering on large data sets, and only render the content of the visible area.

  4. Data request optimization:

  • Use cache: Reasonably use browser cache and server cache to reduce unnecessary data requests.
  • Avoid repeated requests: Avoid repeated requests for the same data multiple times in components, and use state management tools to share data.
  • Batch requests: Merge multiple data requests, reduce network overhead, and use technologies such as GraphQL to control data requests more finely.
  1. Lazy loading: For components or data that are not needed immediately, use lazy loading to load on-demand to avoid loading unnecessary content during initial loading.

  2. Server-side rendering (SSR): For some cases, consider using server-side rendering to generate the initial HTML on the server side, reducing unnecessary client-side rendering.

  3. Performance monitoring and analysis: Use performance monitoring tools to regularly monitor application performance metrics to identify and resolve excessive rendering and unnecessary data requests.

  4. Use framework tools and plugins: Front-end frameworks usually provide many tools and plugins for optimizing performance and avoiding unnecessary rendering. Make sure to familiarize yourself with and take full advantage of these tools.

  5. Review network requests: Use browser developer tools to review network requests for unnecessary requests, such as duplicate or unnecessary data requests.

Through the above methods, you can effectively avoid over-rendering and unnecessary data requests, thereby improving the performance and user experience of front-end applications.

66. Have you ever encountered performance problems caused by too many third-party dependencies? How do you evaluate and handle the selection of third-party libraries and plugins in your project?

Inappropriate or unnecessary third-party libraries and plugins can affect user experience by increasing app load times, complexity, and maintenance costs.

  1. Functional requirements: First, ensure that the selected third-party libraries and plug-ins can meet the functional requirements of the project. Avoid choosing too many libraries with overlapping functions, so as not to add unnecessary complexity.

  2. Community Support and Activity: View community support and activity for a library or plugin. An active community usually means more maintainers and contributors, as well as timely issue resolution and updates.

  3. File size and performance: Assess the file size and performance impact of your library. Choose a library that is small and performs well to avoid loading too much unnecessary code.

  4. Customizability: Some libraries may provide many functions, but you may only need some of them. Make sure the library is customizable enough so that only the required functionality is selected and loaded.

  5. Maintenance quality: View the maintenance quality of the library, including whether the documentation is complete, whether problems are fixed in time, and the frequency of version updates.

  6. Ecosystem Compatibility: Make sure the chosen library is compatible with other libraries and frameworks you use to avoid conflicts and issues.

  7. Is it necessary: ​​Evaluate whether it is really necessary to introduce the third-party library. Sometimes, we can use native solutions to avoid introducing additional libraries.

  8. Performance testing: Before introducing new third-party libraries or plug-ins, perform performance testing to evaluate its impact on application performance.

  9. Update frequency and long-term support: View the library's update frequency and long-term support plan. Choose libraries that are continuously maintained and updated to ensure long-term maintainability of your project.

  10. Maintainability: Consider the code quality and maintainability of the library. An easy-to-read and maintain library reduces potential problems and maintenance costs.

When choosing third-party libraries and plugins, you need to weigh the above factors and make decisions on a project-specific basis. Third-party dependencies used are regularly reviewed and updated to ensure they still meet the needs and performance requirements of the project.

67. Talk about the different levels of front-end cache, including browser cache, CDN cache, server cache, etc. How are you using these caches in your project to improve performance?

Front-end caching plays a key role in improving performance and can significantly reduce data transfer and load times. Here are some of the different tiers of front-end caching and how you can leverage them in your projects to improve performance:

  1. Browser cache:
    Browser cache is one of the most common front-end caching tiers, which saves a copy of static resources in the user's local storage, reducing data transfer time on subsequent visits. Utilizing browser caching in a project can be achieved in the following ways:
  • Set appropriate caching policies: Tell the browser to reuse cached resources for a period of time by setting the resource's cache control headers (such as Cache-Control and Expires).
  • Versioned file name: Include the version number or hash value in the resource URL. When the resource content changes, the URL will change accordingly, thus triggering a new resource request.
  1. CDN cache:
    CDN (Content Delivery Network) is a globally distributed server network that can cache and distribute static resources to speed up resource loading. Utilizing CDN caching in a project can be achieved in the following ways:
  • Use a CDN provider: Deploy static resources to a CDN provider, allowing the CDN to distribute resources to servers closer to users, reducing network transmission time.
  • Set cache time: Set an appropriate cache time through the CDN provider to ensure that resources can be cached on the CDN for a long time and reduce the load on the source server.
  1. Server caching:
    Server caching is saving a copy of a page or data on the server side so that it can be responded quickly on subsequent requests. Utilizing server caching in your project can be achieved in the following ways:
  • Use Reverse Proxy Caching: Cache pages or data on a reverse proxy server (such as Nginx, Varnish) to reduce the load on the origin server and improve response speed.
  • Set cache for specific requests: For specific API requests, you can set cache policies based on request parameters or header information to reduce repeated data queries.
  1. Data caching:
    In addition to caching of static resources, dynamic data can also be cached to avoid unnecessary database queries or calculations. Utilizing data caching in your project can be achieved in the following ways:
  • Use cache middleware: For data query, you can use cache middleware, such as Redis, to cache query results for a period of time to reduce database pressure.
  • Set an appropriate cache expiration time: According to the data change frequency, set an appropriate cache expiration time to ensure the timeliness of cached data.

In the project, combining the above different levels of caching strategies can significantly improve performance, reduce network transmission time, speed up page loading, and provide a better user experience. However, reasonable cache configuration and management needs to be carried out according to the needs and conditions of specific projects.

68. In the development of the mobile terminal, have you encountered performance problems caused by poor network conditions? How do you handle page loads and data requests on slow networks?

In mobile development, poor network conditions can cause performance issues with page loading and data requests. In order to provide a better user experience, some measures need to be taken to handle performance issues in slow network situations:

  1. Optimize resource loading:
  • Image Compression and Format Selection: Use an appropriate image format (such as WebP) and compression tools to reduce image file size.
  • Lazy loading: Lazy loading of images and resources that are not the primary content to be displayed, so that key content is loaded first.
  • Resource preloading: Use preloading technology to load the resources required by the next page or view in advance to improve the response speed of page switching.
  1. Data request optimization:
  • Data compression: For transmitted data, use compression algorithms (such as Gzip) to reduce the amount of data transmission.
  • Data paging and lazy loading: For lists or large data sets, use paging and lazy loading to reduce requesting large amounts of data at one time, thereby improving loading speed.
  • Data cache: For frequently requested data, use a local cache so that some data can still be provided even when the network is disconnected or the network is poor.
  1. Using Server Side Rendering (SSR):
  • For pages that require faster content rendering for the first time, consider using server-side rendering to reduce client-side loading and rendering time.
  1. Progressive Enhancement:
  • Load core content first: Make sure the page loads core content first so that users can quickly access key information.
  • Gradually enhance functions: In a better network environment, additional functions and interactions are gradually loaded and activated to provide a richer experience.
  1. Offline support:
  • Use Service Workers: By using Service Workers technology, you can implement offline access support, so that the application is still available when there is no network connection.
  1. Provide user feedback:
  • Prompt loading status: In the case of slow loading, provide users with loading status prompts to reduce user uncertainty and dissatisfaction.
  1. Performance testing and simulating slow networks:
  • Use a performance testing tool, such as Lighthouse, to simulate a slow network environment, check the performance of the page, and optimize accordingly.

Through the above measures, the loading and performance of mobile pages can be improved under slow network conditions, and a better user experience can be provided.

69. When dealing with dynamic data and real-time communication, how do you optimize the data transmission and rendering efficiency of the front end?

When dealing with dynamic data and real-time communication, it is critical to optimize data transfer and rendering efficiency on the front end to provide a faster and more responsive user experience. Here are some optimization strategies:

  1. Data transfer optimization:
  • Use compression: For large data transfers, use a compression algorithm such as Gzip to reduce the packet size and thus reduce network transfer time.
  • Loading in batches: Transfer data in batches and load gradually to avoid transferring a large amount of data at one time. This works especially well in loading lists or paginated data.
  • Only transmit necessary data: During data transmission, only the fields and information required by the client are transmitted to avoid unnecessary data transmission.
  1. Data processing and transformation:
  • Front-end data processing: Try to put some data processing operations on the front-end to reduce the pressure on the back-end to improve real-time performance.
  • Data format selection: Use a lightweight data format, such as JSON, to reduce data size.
  1. Data cache:
  • Client-side caching: Use local storage or in-memory caching to cache parts of the data on the client side for fast rendering when needed.
  • Server-side cache: For repeatedly queried data, you can use server-side cache, such as Redis, to reduce the frequency of database queries.
  1. Virtualization and paging:
  • Virtual list: For large lists, use a virtual list to render only the visible part to improve page rendering efficiency.
  • Page loading: When a large amount of data needs to be displayed, use page loading, and only load one page of data at a time to avoid loading too much data at one time.
  1. WebSockets and HTTP/2:
  • WebSockets: For real-time communication, use WebSockets technology to establish persistent connections, realize real-time data transmission, and avoid frequent request-response loops.
  • HTTP/2: Using the HTTP/2 protocol, connections can be reused, and multiple requests and responses can be made on the same connection to improve performance.
  1. Avoid unnecessary rendering:
  • Use shouldComponentUpdate (in React): Use the shouldComponentUpdate method to determine whether re-rendering is required before rendering components to avoid unnecessary rendering operations.
  1. Lazy loading and lazy loading:
  • Lazy loading: Lazy loading of dynamic data that is not immediately visible, waiting for the user to load it when needed.
  • Lazy loading: Load specific modules or components when needed, avoiding loading all content that may not be used in the first place.
  1. Performance monitoring and tuning:
  • Use performance monitoring tools: Use tools to monitor data transfer and rendering performance, identify bottlenecks and optimize them.

Using the above strategies comprehensively can effectively optimize the front-end data transmission and rendering efficiency, and provide a faster and real-time user experience. However, specific optimization methods will vary depending on project requirements and technology stacks.

70. Please share a case and experience of your successful optimization of front-end performance in an actual project, as well as the specific measures and improvement effects you have taken.

In a real project, I once dealt with a performance optimization case of a gallery application that needs to load a lot of images. The original version of the application has problems such as long loading time and page freezes when loading a large number of images, which affects the user experience. Here are some steps I took and how they improved:

Problem analysis:
The initial version of the gallery application did not perform any optimization when loading images, and all images were loaded at one time, resulting in long page loading time and freezes.

Optimization measures:

  1. Image Compression and Format Optimization: For each image, use image editing tools to compress and convert the image format from PNG to WebP to reduce image file size. This can improve loading speed by reducing the amount of network traffic.
  2. Lazy loading: Use lazy loading technology to only load pictures in the visible area instead of loading all pictures at once. This reduces the initial load time and increases the rendering speed of the page.
  3. Virtual list: In order to optimize the performance of large image lists, virtual list technology is used to render only the visible part of the image. This reduces the number of DOM elements and rendering effort.
  4. Image preloading: When the page loads, load the next page or preview images in advance to improve the user's browsing experience.
  5. CDN Acceleration: Upload all image resources to CDN, and configure appropriate caching strategies to speed up the loading of images.

Improvement effect:
Through the above optimization measures, the performance of the application has been significantly improved:

  1. Faster load times: Images load times are drastically reduced, pages load faster the first time, and users can browse galleries more quickly.
  2. Smooth experience: Using lazy loading and virtual list technology, the page keeps smooth when scrolling, reducing the stuttering phenomenon.
  3. Increased user satisfaction: Due to the improved loading speed and interaction, user satisfaction has been improved, and users are more willing to browse images in the application.

This case shows how to significantly improve the performance of the front-end application and improve the user experience through the application of image optimization, loading strategy adjustment and performance technology. In actual projects, comprehensive consideration of different aspects of optimization can effectively solve performance problems and provide users with a better experience.

Guess you like

Origin blog.csdn.net/weixin_52003205/article/details/132135766