11

Hello everyone, my name is Tao Weng

In recent interviews, I often ask: How does understand rearrangement and redraw?

I found that many candidates did not answer the key points, and I felt that they had seen relevant articles somewhere, which sounded scattered and illogical.

Error demonstration

The general interview process goes like this:

Interviewer: How do you understand rearrangement and repainting?

Candidate: Reflow is when the structure of the page changes, it will reflow, such as changing the size of the font, adding or deleting DOM elements. Redrawing means that the page structure has not changed, but the appearance has changed, such as changing the font color and background color. Just a repaint will happen.

Of course he is right, and I can't just say he is wrong and continue to guide

Interviewer: Does rearranging have anything to do with redrawing?

Candidate: Reflow will definitely lead to redraw, and redraw will not necessarily lead to reflow.

Interviewer: Why?

Candidate: Because the rearrangement structure has changed, it will definitely lead to a redraw.

This is how I look now:

If you think the above answer is true, then you must take a good look at the following.

Next, I generally won't skip it directly, I will ask the browser key rendering path for guidance.

If you don't know, I will guide you again (in fact, I have basically given up at this time).

Do you know what happens when the browser loads an HTML?

If you still don't know, this is the next question.

If you know the critical rendering path, you can still understand it with a basic guide. If you don't know it, you can't understand rearrangement and redraw.

test center

I generally look at two points in this question:

  1. Browser critical rendering path . If you can't answer the above, the question is generally cold.
  2. Performance optimization, if you reduce redrawing and reflow, of course, this point must also be based on the understanding of the critical rendering path (this is not the key point).

review

The purpose of the review is to know what the test center is. I will simply review it for you. For more detailed content, I hope to follow the knowledge points I introduced (you can read the articles I recommend at the end of this article for in-depth study). After all, review is not a class.

We may know that we can render pages to the screen by writing HTML, CSS, and JavaScript, but how does the browser render our code to the pixels on the screen? This requires understanding such a concept CRP:

Critical Rendering Path ( Critical Rendering Path ) is the sequence of steps a browser goes through to convert HTML, CSS and JavaScript into pixels on the screen. Optimizing the critical rendering path can improve rendering performance.

The general steps are this: When the HTML is parsed, the DOM is created, the HTML can request JavaScript, and the JavaScript, in turn, can change the DOM. HTML contains or requests styles, which in turn builds CSSOM.

The browser engine combines the two to create the Render Tree, the Layout determines the size and position of everything on the page, and after the layout is determined, the pixels are Painted (drawn) onto the screen.

Optimizing the critical rendering path can reduce the time to first render. Understanding and optimizing the critical rendering path is important to ensure that redraw and redraw can be done at 60 frames per second to ensure efficient user interaction and avoid annoying.

Next, study the detailed process:

step

1. Generate DOM

DOM construction is incremental. The browser downloads Byte from remote => converts it to string according to the corresponding encoding (such as utf8) => parses it as Token through AST => generates Node => generates DOM .

A single DOM node starts with a startTag token and ends with an endTag token. Nodes contain all relevant information about HTML elements. This information is described using tokens. Nodes are connected into the DOM tree according to the token hierarchy.

If another set of startTag and endTag tokens is between a set of startTag and endTag, there is a node within a node, and this is how we define the DOM tree hierarchy.

2. Generate CSSOM

The browser parses the css file and generates CSSOM. CSSOM contains all the styles of the page, that is, how to display the information of the DOM.

CSSOM is similar to DOM, but different.

DOM construction is incremental, CSSOM is not. CSS is render-blocking: the browser blocks the page from rendering until it has received and executed all the CSS.

CSS is render blocking because rules can be overridden, so content cannot be rendered until CSSOM is complete.

3. Render Tree

The Render Tree includes content and styles: the DOM and CSSOM trees are combined into a render tree.

To construct the render tree, the browser inspects each node, starting at the root of the DOM tree, and decides which CSS rules to add.

The render tree contains only visible content (the part in the body).

Heads (usually) do not contain any visible information and are therefore not included in the render tree species. If an element has display: none; on it, neither it nor its descendants will appear in the render tree.

4. Layout

Once the render tree is built, layout becomes possible. The layout depends on the size of the screen. The layout step determines where and how elements are placed on the page, determines the width and height of each element, and how they relate to each other.

Tip: A page is rendered on screens of different sizes, such as rendering on a mobile terminal and a PC terminal, and the display is different. The previous steps are the same. Only during the layout will it be differentiated according to the screen size. .

5. Paint

The final step is to draw the pixels to the screen, rasterize all the elements, convert the elements to actual pixels.

Once the render tree is created and the layout is complete, the pixels can be drawn on the screen. When loading, the entire screen is drawn. After that, only the affected screen area of will be redrawn by , and the browser is optimized to only redraw the smallest area that needs to be drawn.

The draw time depends on what type of update is attached to the render tree. Drawing is a very fast process, so it's probably not the most efficient part when focusing on improving performance

Reflow and Repaint

After understanding the above critical path rendering, it is a small case to understand rearrangement and repainting.

  • Reflow: Reflow occurs when the position of of an element changes , also called reflow. in the Layout phase, calculate the exact position and size of each element within the device's viewport. When the position of an element changes, the position of its parent element and the elements behind it may change, at a very high cost .

    When answering what is rearrangement, the key is not that the position changes, it is just the reason (Why), not the What. What is recalculating the exact position and size of each element within the device viewport.
  • : The style of the element has , but the position has not changed. At this point in the Paint phase in the critical rendering path, each node in the render tree is converted into actual pixels on the screen, a step commonly known as painting or rasterization.

    The key to answering what is redrawing is in the Paint phase in the critical rendering path, converting each node in the rendering tree into actual pixels on the screen, which is What.

JavaScript and critical path rendering

When we talked about the steps, we basically talked about the relationship between HTML, CSS and CRP. Finally, let’s talk about the relationship between JS and CRP, and then look at the picture at the beginning of the article.

The execution of JavaScript is before the rendering tree is generated. This is why the loading, parsing and execution of JavaScript blocks the construction of the DOM and the rendering of the page.

This is actually very reasonable

Because JavaScript can modify the content of web pages, it can change the DOM. If it does not block, then the DOM is being constructed here, and the DOM is being modified by JavaScript over there. How to ensure that the final DOM is correct?

And in JS, what is the difference between the DOM obtained in the first second and the DOM obtained in the next second? It will cause a series of problems, so JS is blocking, it will block the construction process of DOM, so the elements behind JS cannot be obtained in JS, because the DOM has not been constructed yet.

This is why we need to put js at the bottom of the page, and try to ensure that the DOM tree is generated before loading the JS, so that this effect occurs.

performance optimization

Based on the above analysis, I will briefly talk about a few performance optimization methods. You can analyze why these methods can be used for performance optimization.

  1. Reduce DOM tree rendering time (such as lowering the HTML level, making tags as semantic as possible, etc.)
  2. Reduce CSSOM tree rendering time (lower selector levels, etc.)
  3. Reduce the number of HTTP requests and request size
  4. Put css at the beginning of the page
  5. Put js at the bottom of the page, and use defer or async as much as possible to avoid blocking js loading, and ensure that JS is loaded only after the DOM tree is generated
  6. Replace @import with link
  7. If the page has less CSS, try to use inline
  8. In order to reduce the white screen time, a DOM tree is quickly generated when the page loads

Correct performance optimization ideas

Let’s talk about performance optimization again. When you encounter a performance problem, you definitely don’t go to the Internet to find some performance optimization methods, and then no matter the three, seven, twenty-one, just straighten it up, which is very likely to be useless.

The first thing to do is to analyze where the performance bottleneck is.

The first thing to do is to analyze where the performance bottleneck is.

The first thing does is to analyze where the performance bottleneck is.

For example, if you encounter the performance problem of loading on the first screen, you need to use developer tools, such as to see whether the network is slow in requests due to too large resources, slow back-end processing, or too many resources and slow loading.

If these are not, it may be because the rendering is slow, and then analyze the performce panel to see if the js execution is slow or what is the reason.

Another example is that you encounter performance problems with webpack. For example, the packaged resources are too large. If you have to solve this problem, you should not just find a few optimization methods and start the adjustment.

Instead, what is the reason for analyzing the package size through the webpack-bundle-analyzer plugin?

  • Is the dependency package too large and not loaded on demand?
  • Or do you repeatedly package several versions of the same dependencies?
  • Or because the src is too large, do you need to do a dynamic loading?
  • Or because of other things, find the problem through the composition content analyzed by webpack-bundle-analyzer.

Finally, let me summarize. When encountering a problem, you should first use various analysis tools to find the cause of the performance bottleneck, and then find the corresponding optimization method based on this reason, and prescribe the right medicine.

Whether it’s an answer during an interview, or when you usually deal with a problem, you only need to analyze the problem and find a lot of solutions. If you can’t find the problem, messing around is a waste of time.

reference answer

I believe that after the review, you should be clear about this knowledge point. You don’t need to say so much during the interview. Just say the key points and let the interviewer know that you understand it. If the interviewer is interested, he will continue to ask questions. , at this time, I will introduce to him in detail the points of inquiry.

If I were asked this question, my answer would be something like this, just for reference:

Reordering and redrawing are two nodes on the key rendering path of the browser. The key rendering path of the browser is DOM and CSSOM to generate a rendering tree, and then determine all the content on the page through a layout (also called layout) step according to the rendering tree. After determining the size and position of the layout, the pixels are drawn (also called Paint) to the screen.

Rearrangement means that when the position of the element changes, the browser re-executes the layout step to re-determine the size and position of the content on the page. After the determination, it will be redrawn to the screen, so rearranging will definitely lead to redraw.

If the position of the element has not changed, but only the style has changed, the browser will skip the layout step and go directly to the drawing step when re-rendering.

With the above answer, I think most interviewers can already get the score for this question.

However, it is still possible for the interviewer to continue to ask in-depth questions. friends can tell us what related problems you have encountered in the comment area, and I will continue to help you analyze together later.

For performance issues, it is not so important to reduce redrawing and reflow, because the general situation of optimization is not very obvious, and the problem of not answering is not a big problem. More performance optimization is the optimization of the entire link, such as the performance optimization title. Those 8 points.

finally

When the industry is down, I hope everyone can find a suitable job smoothly.

Regarding critical path rendering, rearrangement, and redrawing, I finally couldn't help recommending two articles by Mr. Damo, and read them when you have time.

Reference article:

This article participated in the SegmentFault Sifu essay "How to "anti-kill" the interviewer?", you are welcome to join.
Welcome to my public account "Front-end Taoyuan"

leexiaoran
2k 声望1k 粉丝