본문 바로가기

JavaScript

Understanding Repaint and Reflow in JavaScript

 

브라우저 엔진의 주요 역할은 HTML 문서와 웹 페이지의 기타 리소스를 사용자 기기에서 시각적으로 표현하는 것입니다.  브라우저 엔진외에도 관련 개념과 관련하여 두가지 다른 용어가 일반적으로 사용됩니다. 

 

브라우저 엔진 외에도 관련 개념과 관련하여 두가지 다른 용어가 일반적으로 사용됩니다. 레이아웃 엔진렌더링 엔진입니다. 이론적으로는 레이아웃과 렌더링(또는 "페인팅")을 별도의 엔진에서 처리할 수 있습니다. 그러나 실제로는 긴밀하게 결합되어 있으며 분리하여 고려하는 경우는 거의 없습니다. 

 

어떤 링크나 URL 브라우저에서 엔터키를 누르면 해당 페이지에 HTTP 요청을 하고 해당 서버는 HTML 문서를 응답으로 제공합니다. 

 

 

 

- 브라우저는 HTML 소스코드를 구문 분석하여 모든 HTML  태그에 해당하는 노드가 트리에 있고 태그 사이의 텍스트 청크에도 텍스트 노드 표현이 있는 데이터 표현인 DOM 트리를 구성합니다. DOM 트리의 루트 노드는 문서 엘리먼트 <html> 태그 입니다.

- 브라우저는 CSS 코드를 구문 분석하고 이해합니다. 기본 규칙은 사용자 에이전트 스타일 시트(브라우저 기본값)에 있으며, 사용자 스타일시트, 작성자(페이지 작성자와 같은) 스타일 시트(외부, imported, 인라인), 마지막으로 HTML 태그의 스타일 속성으로 코딩된 스타일이 있을 수 있습니다. 

- Then comes the interesting part - Constructing a Render Tree. The render tree is sort of like the DOM Tree but doesn't match it exactly. The render tree knows about styles, so if you're hiding a div with display: none, it won't be represented in the render tree. Same for the other invisible elements, like head and everything  in it. On the other hand, there might be DOM elements that are represented with more than one node in the render tree-like text nodes for example where every line in a <p> needs a render node. A node in the render tree is called a frame, or a box(as in a CSS box, according to the box model). Each of these nodes has the CSS box properties -width, height, border, margin, etc.

- 렌더링 트리가 구성되면 브라우저는 화면에 렌더링 트리 노드를 Paint(draw)할 수 있습니다. 

 

렌더링 트리의 루트 노드는 다른 모든 요소를 포함하는 프레임(상자)입니다. 페이지가 펼쳐질 수 있는 제한된 영역이므로 브라우저 창의 안쪽 부분이라고 생각하면 됩니다. 기술적으로 WebKit은 루트 노드 RenderView를 호출하며, 이는 기본적으로 페이지 상단(0, 0)에서 (window.innerWidth, window.innerHeight)까지의 뷰포트 사각형인 CSS initial containing block에 해당합니다.

 

화면에 정확히 무엇을 표시할지 결정하려면 렌더 트리를 재귀적으로 따라 내려가야 합니다.

 

Repaint and Reflow

페인트와 함께 항상 하나 이상의 초기 페이지 레이아웃이 있습니다. 그 후 렌더링 트리를 구성하는데 사용된 입력 정보를 변경하면 이 중 하나 또는 둘 모두가 변경될 수 있습니다.

 

1. 렌더 트리의 일부(또는 전체 트리)의 유효성을 다시 검사하고 노드 치수(dimensions)를 다시 계산해야 합니다. 이를 리플로우 또는 레이아웃이라고 합니다.(Note that there's at least one reflow - the initial layout of the page.)

2. 노드의 기하학적 속성이 변경되거나 배경색 변경과 같은 스타일 변경으로 인해 화면의 일부를 업데이트해야 할 수도 있습니다. 이러한 화면 업데이트를 repaint, redraw라고 합니다.

 

Repaints and Reflows can be expensive, they can hurt the user experience, and make the UI appear sluggish.

Repaint

As the name suggests repaint is nothing but the repainting element on the screen as the skin of element change which affects the visibility of an element but do not affects layout.

Example.

1. Changing visibility of an element.

2. Changing an outline of the element.

3. Changing the background.

Would trigger a repaint

 

Opera에 따르면 Repaint는 브라우저가 다른 모든 돔 노드의 가시성을 확인/점검해야 하므로 비용이 많이 떨어지는 작업이라고 합니다.

 

Reflow

Reflow means re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. Because reflow is a user-blocking operation in the browser, it is useful for devleopers to understand how to improve reflow time and also to understand the effects of various document properties(DOM depth, CSS rule efficiency, different types of style changes) on reflow time. Somethimes reflowing a single element in the document may require reflowing its parent elements and also any elements which follow it.

 

Virtual DOM vs Real DOM

DOM이 변경될 때마다 브라우저는 CSS를 다시 계산하고, layout, repaint과정이 필요합니다. 실제 DOM에서는 이렇게 시간이 걸립니다. 이 시간을 최소화하기 위해 Ember는 키/값 관찰 기법(key/value observation)을 사용하고 Angular는 더티 체킹을 사용합니다. 이 기법을 사용하면 변경된 돔 노드 또는 Angular의 경우 더티로 표시된 노드만 업데이트할 수 있습니다.

 

그렇지 않은 경우에는 Gmail에서 새 이메일을 작성하는 동안 새 이메일이 도착하자마자 볼 수 없습니다. 

 

하지만 요즘 브라우저는 화면을 다시 칠하는데 걸리는 시간을 단축하기 위해 노력하고 있을 정도로 똑똑해지고 있습니다. 가장 큰 방법은 다시 칠하는 DOM 변경을 최소화하고 일괄 처리하는 것입니다. DOM의 변경사항을 줄이고 배칭하는 전략은 리액트의 Virtual DOM을 뒷받침하는 아이디어입니다. 

 

React doesn’t really do anything new. It’s just a strategic move. What it does is It stores a replica of real DOM in memory. When you modify the DOM, it first applies these changes to the in-memory DOM. Then, using it’s diffing algorithm, figures out what has really changed.

Finally, it batches the changes and call applies them on real-dom in one go. Thus, minimizing the re-flow and re-paint.

 

 

 

 

Understanding Repaint and Reflow in JavaScript

In this post, I’ll try to answer what exactly repaint and reflow is and doe’s really Real DOM is faster than React’s Virtual DOM?

medium.com