[Front-end performance optimization] Front-end optimization unlocks skills to help improve page performance and user interaction experience

The ultimate new performance optimization of the front end

Preface

With the continuous development of web applications, 前端性能优化it has gradually become a required course for mobile and PC development. In real business scenarios, optimization is controlled within milliseconds. Optimization in different dimensions requires the combination of different professional fields and technical skills. Only in this way can we truly strive for excellence and continuously improve page performance.

So, what are the optimization points for front-end performance optimization? In what aspects can further improvements be made?

1. Network performance optimization

The performance bottlenecks of Web applications often appear in two aspects: the first is the number of resources required by the Web application and the request size of each resource . This is because of HTTPthe limitations of the protocol itself, which uses clear text to transmit data, which inevitably creates some performance bottlenecks.

Then, in terms of network performance optimization, we can start from the following aspects:

1. Compress resources

In the process of Web development, we can reduce download time and transmission traffic through the compression of resources suchHTML as , CSS, , JavaScriptand JSON. At the same time, by caching these compressed resources, we can further improve the user's access speed.

2. Merge resources

Optimization experience in web development tells us that the better we do at merging resources, the more delays caused by repeated requests can be reduced. Therefore, in the project, some 合并资源strategies need to be adopted, such as merging multiple CSSor JSfiles into one, reducing HTTP requests , speeding up page loading, and shortening the browser's response time.

3. CDN acceleration

Use CDNto deliver content faster while reducing costs. The core advantage of CDN is that each visitor downloads the content closest to their physical location , which greatly reduces the time and latency(latency) of file downloads, optimizes the network connection layer, and accelerates the access speed of the entire website.

2. Page rendering performance optimization

When network performance reaches optimal levels, we can further optimize page rendering performance from the following three aspects.

1. Optimize the use of images

a. Picture selection
  • For devices with different resolutions and pixel densities, 选择合适的图片格式和大小avoid unclear images that are too large or too small, especially optimize images on mobile devices to reduce download time and space.
b. Use WebP format images
  • WebP 格式It is a new image format that combines the advantages of JPEG, PNG, and has better compression effects . At the same time, it will be better optimized for the loading and startup of medium and large images , which can greatly shorten the loading time of the page. In general, using the format can effectively optimize the rendering performance of the page.GIFWebP
c. Use lazy loading of images

In the picture display on mobile web pages, 图片懒加载思想it has almost become a universal standard. If a page needs to display a large number of images, loading all the images when you first open the page is a waste of resources and affects the loading speed of the page. At this time, you can try to use the lazy loading method of images, and wait until the image is about to appear on the screen . Loading is triggered again within the specified time , thereby speeding up page rendering.

2. Optimization of HTML, CSS and JavaScript

  • In the process of processing HTML, CSSand , reduce the number of elements, optimize code logic, reduce unnecessary calculations, and minimize operations and triggers .JavaScriptDOM
  • For JavaScriptoptimization, minimize the use of classes and functions and use native JavaScript built-in methods as much as possible .
  • For CSSoptimization, you can consider usingBEM excellent methods such as formatting schemes .

3. Optimization of rendering process

  • Avoid excessive redrawing and reflowing operations by minimizing the number of DOM operations and choosing an appropriate rendering method .
  • Optimize some expensive operations : issues such as layout and size calculations , processing and optimization processes, and custom rendering modes.
  • During the development process, we can also use many mature frameworks and libraries , which allow us to implement optimization more conveniently. Under the premise of ensuring the effect, we can write optimization in a simpler way.

For example, for the imported data, we can use the streaming media transmission protocol ( TCP) , use React Nativeto develop native applications, use JPEGXRpictures in the format, and use WebPpictures in the format, etc. Moreover, during the implementation process, we can choose to use webpackpackaging tools and front-end libraries such as to improve development efficiency.

  • DOM fragmented update : If for a very large and frequently updated form DOM(such as JSON 树a form), not only each operation will cause a large number of rearrangements and redraws, but also consume a large amount of performance resources, in this case DOM operations can be used Fragmented update method. That is to say, the DOM structure is split into several small pieces in a certain way and updated . In this way, refined operations can be achieved and unnecessary resource consumption can be reduced.

3. JavaScript execution efficiency optimization

JavaScript optimization is one part of this that focuses on making scripts run faster. Here are some tips and methods to optimize the execution efficiency of JavaScript code.

1. Reduce the number of function calls

The number of JS function calls is an important reason for performance degradation. Therefore, when writing JavaScript code, we should try to reduce the number of function calls as much as possible. When working with loops, it's often faster if you don't call a function but run the code directly inside the loop.

2. Reasonably choose the circulation method

In JavaScript, we have many looping methods, such as for, for in, while, etc. When operating on arrays or objects, you should choose the most appropriate loop method. For array traversal operations, using a for loop is significantly faster than for in and forEach, while for object traversal operations, for in is faster than for.

3. Use object pool

In JavaScript, creating and destroying objects is very common. However, creating and destroying large-scale objects consumes a lot of memory, which affects the performance of the code. At this time, the object pool can be used to cache already created objects to avoid repeated creation.

4. Mobile terminal performance optimization

In web development, mobile performance optimization may be an insurmountable obstacle for many developers. The key points of mobile terminal performance optimization can be roughly divided into the following aspects:

1. Image optimization

For mobile devices, their resolution and pixel density are different from traditional PC devices. Therefore, by optimizing images for different resolutions and pixel densities, you can greatly reduce the size of the image to be transmitted and the network load, while ensuring the display effect of the image on mobile devices.

2. Choose appropriate CSS rules

In mobile web pages, the application of CSS rules is very important. Reasonable application of CSS styles can greatly improve the performance of page rendering. Therefore, in mobile optimization, we should avoid nested use of styles and unnecessary repeated definitions as much as possible.

3. Compress files

Based on the characteristics of mobile devices, you can use Gzip and other compressed file methods to further reduce the amount of transmitted data and network load. In particular, optimization processing for JS and CSS presentation is more effective, which can reduce the size of transmitted data to a certain extent.

During the process, we can choose to use packaging tools and front-end libraries such as webpack to improve development efficiency.

5. Some specific examples of optimization implementation:

1. Minify JavaScript and CSS

During webpackthe build process, you can use uglifyjs-webpack-pluginplugins to compress javascriptthe code, and extract-text-webpack-pluginplugins to extract css and build separate files and compress them.

2. Merge JavaScript and CSS

During webpackthe build process, you can use webpack-mergeplug-ins to merge different JSONfiles, merge separate cssand jsfiles for each page, reduce HTTPthe number of requests, and optimize page rendering performance.

3. Image optimization

You can use image-webpack-loaderto compress and optimize images, provide pixelsizeand qualityfunctions to further control the size and quality of images, and optimize page rendering performance.

4. CDN acceleration

When using CDN, you can add https://cdn.example.com/the prefix to avoid wasting time on other domain names and optimize website performance.

5. Optimize FCP indicators

  • Eliminate blocking resources
  • Minify CSS
  • Remove unused CSS
  • Pre-connected to required source
  • Reduce server response time (TTFB)
  • Avoid multiple page redirects
  • Preload critical requests
  • Avoid huge network load
  • How to use efficient caching strategies to cache static resources
  • Avoid DOM being too large
  • Minimize critical request depth
  • Ensure text remains visible during web font loading
  • Keep the number of requests low and the transfer size small

6. Optimize LCP indicators

LCP is mainly affected by four factors:

  • Slow server response speed
  • JavaScript and CSS render blocking
  • Resource loading time
  • Client rendering

Implementation plan:

  • Use PRPL mode to achieve instant loading
  • Optimize critical rendering path

7. Optimize CSS

  • Defer non-critical CSS
  • Minify CSS
  • Extract key CSS
  • Optimize CSS background images and media queries

8. Optimize your images

  • Choose the right image format
  • Choose the right compression level
  • Compress images using Imagemin
  • Use video instead of gif animation to speed up page loading
  • Provide responsive images
  • Provide images with correct dimensions
  • Using WebP images
  • Optimize images using image cdn Optimize web fonts

9. Ensure text remains visible while web fonts are loading

  • Avoid invisible text during font loading

10. Optimize WebFont loading and rendering

  • Reduce web page font size

11. Optimize your JavaScript (for client-side rendered sites)

  • Use PRPL mode to achieve instant loading
  • Reduce JavaScript size
  • Reduce JavaScript execution time
  • Reduce JavaScript payload with code splitting
  • Remove unused code

6. Common performance optimization strategies

1. Compress and merge files

In front-end development, we usually use multiple CSSand JavaScriptfiles to implement different functions and styles. However, an excessive number of such files will cause multiple network requests, which will affect the loading speed of the application. To solve this problem, we can use the strategy of compressing and merging files . By using tools such as Webpackor Parcel, we can merge multiple files into one or a few files and compress these files to reduce the file size and the number of network requests.

2. Image optimization

Images are often one of the elements in front-end applications that consume a lot of bandwidth and load time. In order to reduce the impact of images on performance, we can adopt some image optimization strategies.

  • First, we can use appropriate image formats , such as JPEG, PNGor WebP, to reduce the file size.
  • Secondly, we can use image compression tools to reduce the quality of images while maintaining visual effects.
  • In addition, lazy loading technology can also be applied to images, loading them only when they enter the visible area to reduce initial loading time.

3. Caching strategy

Taking advantage of your browser's caching mechanism can significantly improve your application's loading speed.

  • By setting appropriate cache header information , you can set a cache policy on the server or browser side to allow the client to cache static resource files within a certain period of time and reduce the number of requests to the server. (Static resources have been cached, and there is still room for optimization)

You can NGINXadd the following configuration to the static resource strong cache 7days
Insert image description here

  • For static resources that are not updated frequently, such as CSS, JavaScript, and image files, we can set a longer cache time to reduce requests to the server.
  • For dynamic content that is updated frequently, we can update the URL of the resource with a version number or hash value to force the browser to re-download the latest version of the file.

4. Delayed loading and lazy loading

Most of the content in a front-end application is not required on initial load. Through lazy loading and lazy loading strategies, we can reduce the initial loading content to a minimum and load it when the user needs it.

  • Lazy loading can be applied to JavaScriptfiles and files 第三方插件, loading and executing them only when needed.
  • Lazy loading can be applied to 图片and 其他大型资源only load when they enter the visible area to improve initial loading speed.

5. Code optimization and performance monitoring

In addition to the above optimization strategies, we should also pay attention to the quality and performance of the code.

  • By optimizing JavaScriptthe code , such as reducing unnecessary calculations, avoiding repeated operations and using efficient algorithms, we can improve the execution efficiency of the application.
  • In addition, using performance monitoring tools and browser developer tools , we can analyze and monitor application performance indicators such as load time, CPU usage, and memory usage, as well as identify potential performance bottlenecks and optimize them.

6. Concurrent request limit

You can limit the number of concurrent requests to avoid excessive server load, resulting in slower response times.
(Most interfaces have no restrictions. If someone performs a stress test on the interface, it will cause slow response)

7. Upgrade HTTP2 (this is not easy, HTTP2 IE does not support, HTTPs is required)

8. Reduce HTTP requests and merge duplicate requests

9. Increase server costs and adopt load balancing and other technologies

10. Use CDN technology (due to internal systems, which are often deployed on a single machine, this has not been implemented)

Caching static resource files on CDNservers around the world can improve access speed and reduce server load.

Summarize:

前端性能优化is Weban important aspect of development. Its goal is to improve page response speed , speed up page loading , reduce the time required for page operations and improve user experience . When the optimization effect is not obvious and can be eliminated one by one, the best way is to start from the overall perspective, start from multiple aspects, combine with actual business scenarios and practices, and focus on improving efficiency , so that we can truly achieve excellence and performance optimization. further improvement.

前端性能优化You can start from two aspects: optimizing network performance and page rendering performance , including resource compression and merging , using CDN acceleration , image optimization and HTML, CSS and JavaScript optimization , optimizing the rendering process , using mature tools and frameworks, and Provide high-performance cloud services , etc. When building a project, you can further improve page performance and user interaction experience by optimizingCSS, ,JavaScriptandHTML, optimizingwebpackpackage files and usingWebP,Woff, ,JPEGXRand , while providing a better user experience.

Guess you like

Origin blog.csdn.net/weixin_55846296/article/details/128406003