How to optimize front-end performance

Recommended websites for essential front-end tools (free image beds, APIs, ChatAI and other practical tools):

http://luckycola.com.cn/

Foreword:

Front-end performance optimization has always been a classic topic that front-end developers must pay attention to. Although with the continuous development of technology, the performance of web page containers (browsers, webviews) is becoming more and more powerful, but the functions of website applications are also constantly enriched, and the size is not large. To avoid the increase, when the network environment and other factors are not good, there will still be problems that seriously affect the user experience such as long white screen time. Therefore, understanding the performance optimization of the front-end is imperative, and it is also an important part of the front-end job interview. Frequently Asked Questions. Today we discuss this issue in depth.

1. The principle of page rendering

We often encounter interviewers asking this question during interviews: Do you know what the browser does to render a page?

In fact, this is a very classic question in front-end inspections, and it is also the core background question for our discussion today on " how to optimize front-end performance ." We need to know: all solutions for optimizing front-end performance must start from the root of the problem. . Therefore, in order to optimize the performance of the front-end, you must understand the cause of the problem, and then you need to simply understand the principle of page rendering.

If the entire process of the browser rendering the page is divided into two, the first step is mainly the part where the browser requests the resources required to render the page; the second step is when the browser obtains the resources and optimizes the rendering part.

The first part mainly depends on environmental factors such as network, and the second part depends on the optimization factors of "Critical Rendering Path " . It is also the part of the optimization plan that we need to focus on:

Critical Rendering Path Diagram

(1)、Dom tree

The DOM is not only accessible through JS. Scalable vector graphics SVG, mathematical markup language MathML and synchronous multimedia integration language SMIL have added DOMmethods and interfaces unique to the language. Once the HTML is parsed, a DOM tree is built . The code below has three regions: header, mainand footer. And style.cssfor external files .

When the above code is parsed into a structure HTMLby the browser , the relationship of each node is as follows.DOM树

(2)、CSSOM Tree

CSSOMAlso an object-based tree. It is responsible for handling styles related to the DOM tree .

For the above CSS declaration, CSSOM树it will appear as follows.

Since csssome attributes of , can be inherited , if the attributes defined in the parent node meet the conditions, the child nodes will also have corresponding attribute information, and finally the corresponding style information will be rendered on the page. '

(2)、Render Tree:

While the browser is constructing the DOM tree, it is also constructing another tree - the Render Tree. Its main function is to display HTML according to a certain layout and style, using CSS-related knowledge. From the perspective of MVC, the render tree can be regarded as V, the dom tree can be regarded as M, and C is the specific scheduler, such as HTMLDocumentParser.

2. Front-end performance optimization practice

(1) Rendering critical path optimization

(1) The size of HTML files should be as small as possible:

The purpose is to allow the client to receive the complete HTML as early as possible. Usually there are a lot of redundant characters in HTML,

For example: JS comments, CSS comments, HTML comments, formats, and newlines. What's worse is that I've seen a lot of HTML in production environments that contains a lot of obsolete code. This may be because as time goes by, the project gets bigger and bigger, and problems left over from history for various reasons, but anyway , this is all bad. For HTML in a production environment, useless code should be removed to ensure that the HTML file is as streamlined as possible.

(2) Optimize CSSOM and rendering-blocking CSS

CSS is an essential element for building a render tree, and when first building a web page, JavaScript is often blocked by CSS. Make sure that any non-required CSS is marked as non-critical resources (such as printing and other media queries) ( Figure 3.1 ), and should ensure that the amount of critical CSS is reduced as much as possible, and the delivery time is as short as possible.

In addition to the optimization strategies mentioned above, CSS has another factor that can affect performance: CSS blocks the critical rendering path. CSS is a critical resource, and it's not surprising that it blocks the critical rendering path, but usually not all CSS resources are so "critical".

For example: some responsive CSS will only take effect when the screen width meets the conditions, and some CSS will only take effect when the page is printed. These CSS will not take effect when they do not meet the conditions, so why do we let the browser wait for CSS resources that we do not need?

Figure 3.1

(3) Avoid using @import in CSS

Everyone should know to avoid using @import to load CSS, and we will not load CSS like this in actual work, but why?

This is because loading CSS using @import adds extra critical path length. for example:

  • As shown in Figure 4.1, when you link a style.css in an index.html file, and then import a main.css file in style.css, the two dependent files are loaded serially. The loaded style file is The sum of the time spent on the two files (Figure 4.2)

Figure 4.1:

Figure 4.2:

  • As shown in Figure 4.3 , if style.css and main.css are directly imported by link in index.html, then they are loaded in parallel, which is the loading time of the file that takes longer (Figure 4.4)

(4) Optimize the way to load js files

When the browser encounters Scripe during the HTML parsing process, it will block the HTML page rendering, send the page request, pass the JS script code, and then hand it over to the JS engine to execute the code. When the execution is completed, the browser will continue to parse the HTML. The schematic diagram is as follows:

  • After loading the js file, although it does not block the html, it still cannot reduce the duration

  •  

  • Use the async keyword to load js files asynchronously, but js execution will still block html loading

  • Use the defer keyword to load js files asynchronously, but the js execution will be delayed and will not block html loading

  • In addition, there are common solutions such as preload and prefetch.

(2) Appropriate use of design pattern optimization

(1) Use singleton mode to prevent repeated instantiation

Many times we are only allowed to instantiate one class with fixed functions on a page. This not only facilitates the readability and maintainability of the code, but also ensures performance overhead to a large extent and reduces memory load pressure. So how to ensure that only one class is allowed to be instantiated? What about classes? Examples are as follows

(2) Use flyweight mode for big data node rendering (paging and other scenarios)

In actual development scenarios, we often encounter the need for big data front-end rendering nodes such as paging, but we know that direct operation of front-end js is the most performance-consuming behavior. In order to save performance overhead, we should try our best to Reduce direct operations on dom nodes. Based on this starting point, the flyweight pattern in the design pattern provides us with a good solution.

Next, let’s take a look at the paging logic without using flyweight mode:

The code after using flyweight mode is as follows:

It is worth noting that:

No matter how large the amount of data is in Flyweight mode, the code directly operates only those 5 DOM nodes. The paging behavior does not repeatedly add additional DOM nodes, but only modifies the contents of the same 5 nodes. The 5 nodes are always It is shared. If the Flyweight mode is not used, the same number of DOM nodes will be created and the display attribute will be switched based on the amount of data. The performance consumption of the two solutions is obvious.

(3), Appropriate use of throttle ( throttling ) and anti-shake ( debounce )

Anti-shake and throttling are usually used as means of project optimization, generally to prevent users from triggering action execution by performing multiple operations quickly and frequently in a short period of time. For example, it prevents users from clicking the submit button multiple times, triggering the form to be submitted multiple times; preventing users from pulling the scroll bar, triggering more loads multiple times, etc.

The characteristic of debounce is that when events are triggered in rapid succession, the action will only be executed once.

Anti-shake and throttling are essentially different. Anti-shake is triggered multiple times but will only be executed once, throttling is triggered multiple times but will only be executed once in a cycle

throttling, the throttling strategy is to only perform one action no matter how many times the event is triggered in each time period. After the previous time period ends, another event is triggered and a new time period starts. Similarly, the new time period will only perform one action.

In addition, there are many design patterns. If you are interested, you can read the book "JavaScript Design Patterns". Here are just a few classic examples.

(3) Other common optimization solutions

(1), lazy loading

Resource lazy loading

The key to loading is "lazy loading". Any media resource, CSS, JavaScript, image, or even HTMLcan be lazy loaded. Loading limited page content at a time can improve the critical rendering path.

  • Don't load this whole page's CSS, JavaScriptand HTML.

  • Instead, you can add an event listener for one buttonand only load the script when the user clicks the button.

  • Use Webpackto complete the lazy loading function.

Here are some techniques for lazy loading using pure JavaScript.

For example, now another one <img/>/<iframe/>. In these cases, we can take advantage <img>of the default attributes<iframe> that come with the tag . When the browser sees this tag, it defers loading and .loadingiframeimage

(2) Reasonable use of web worder

As we all know, JavaScript is executed in a single thread. All tasks are executed on one thread. The next task can only be processed after the current task is executed. Otherwise, the following tasks can only wait, which limits the full use of the computing power of multi-core computers. At the same time, on the browser, JavaScript execution is usually located on the main thread, which happens to be together with style calculation, page layout and drawing. If JavaScript runs for too long, it will inevitably cause other work tasks to be blocked and cause frame loss.

To this end, some pure computing work can be migrated to Web Worker, which provides a multi-threaded environment for JavaScript execution. The main thread can share part of its own task execution pressure by creating Worker sub-threads. Tasks executed on the Worker sub-thread will not interfere with the main thread. After the task is completed, the results will be returned to the main thread. This has the advantage that the main thread can focus more on processing UI interactions and ensure the use of the page. Experience the process.

(3) Skeleton screen optimizes the white screen duration

Using a skeleton screen can shorten the white screen time and improve user experience. Most mainstream websites in China use skeleton screens, especially SPA single-page applications on mobile phones. Regardless of Vue or React, the initial HTML is blank, and the content needs to be mounted to the root node by loading JS. This set Side effects of the mechanism: It will cause a long-term white screen. Common skeleton screen plug-ins are based on this principle. When packaging the project, the content of the skeleton screen is directly placed in the root node of the html file. Using the skeleton screen plug-in, the packaged html file (The inside of the root node is a skeleton screen):

For the same project, compare the FP white screen time before and after using the skeleton screen:

  • Skeletonless screen: long white screen time

  • There is a skeleton screen: when the screen is white

Skeleton screen plug-in recommendation: vue-skeleton-webpack-plugin

Conclusion

Front-end performance optimization has always been a classic topic in the field of front-end development. With the development of technology, more and more solutions have emerged. Due to the limited length of the article, only some classic optimization solutions are discussed here. If you are interested, you can check out more Share more information and books.

Guess you like

Origin blog.csdn.net/qq_48896417/article/details/131266145