What's Critical Rendering Path?
The Critical Rendering Path is the sequence of steps the browser goes through to convert the HTML, CSS, and JavaScript into pixels on the screen.
Why is it important?
Optimizing the critical rendering path improves the time to first render.
The Rendering Proccess
- A request for a web page or app starts with an HTTP request.
- The server sends a response containing the HTML.
- The browser then begins parsing the HTML, converting the received bytes to the DOM tree.
- The browser initiates requests every time it finds links to external resources, be it stylesheets, scripts, or embedded image references.
- Some requests are blocking, which means the parsing of the rest of the HTML is halted until the imported asset is handled.
- The browser continues to parse the HTML making requests and building the DOM, until it gets to the end, at which point it constructs the CSS object model.
- With the DOM and CSSOM complete, the browser builds the render tree, computing the styles for all the visible content.
- After the render tree is complete, layout occurs, defining the location and size of all the render tree elements.
- Once complete, the page is rendered, or 'painted' on the screen.
[1] DOM (Document Object Model)
DOM construction
- incremental
- HTML response -> tokens -> nodes -> DOM Tree
A single DOM node starts with a startTag token and ends with an endTag token. Nodes contain all relevant information about the HTML element. The information is described using tokens. Nodes are connected into a DOM tree based on token hierarchy. If another set of startTag and endTag tokens come between a set of startTag and endTags, you have a node inside a node, which is how we define the hierarchy of the DOM tree.
- The greater the number of nodes, the longer the following events in the critical rendering path will take.
[2] CSSOM (CSS Object Model)
- The DOM contains all the content of the page. The CSSOM contains all the information on how to style the DOM.
- While the DOM construction is incremental, CSSOM is not.
- CSS is render blocking:
- the browser blocks page rendering until it receives and processes all the CSS.
- CSS is render blocking because rules can be overwritten, so the content can't be rendered until the CSSOM is complete.
- The incremental processing features don't apply to CSS like they do with HTML, because subsequent rules may override previous ones.
- CSS is render blocking:
- In terms of selector performance, less specific selectors are faster than more specific ones.
- For example, .foo {} is faster than .bar .foo {} because when the browser finds .foo, in the second scenario, it has to walk up the DOM to check if .foo has an ancestor .bar.
- The more specific tag requires more work from the browser, but this penalty is not likely worth optimizing around.
- When it comes to CSS, selector performance optimization improvements will only be in microseconds.
[3] Render Tree
- The render tree captures both the content and the styles :
- the DOM and CSSOM trees are combined into the render tree.
- The render tree only captures visible content.
- The head section (generally) doesn't contain any visible information, and is therefore not included in the render tree.
- If there's a display: none; set on an element, neither it, nor any of its descendants, are in the render tree.
[4] Layout
- Layout is dependent on the size of screen.
- The layout step determines where and how the elements are positioned on the page, determining the width and height of each element, and where they are in relation to each other.
- The viewport meta tag defines the width of the layout viewport, impacting the layout.
- Layout happens every time a device is rotated or browser is otherwise resized.
- The device-width changes when a user rotates their phone between landscape and portrait mode.
- Layout happens every time a device is rotated or browser is otherwise resized.
- Layout performance is impacted by the DOM — the greater the number of nodes, the longer layout takes.
- Layout can become a bottleneck, leading to jank if required during scrolling or other animations.
- Any time the render tree is modified, such as by added nodes, altered content, or updated box model styles on a node, layout occurs.
- To reduce the frequency and duration of layout events, batch updates and avoid animating box model properties.
- batch updates? => 업데이트를 일괄 처리?
- 여러 DOM 변경 사항을 한 번에 적용함으로써 브라우저가 불필요하게 여러 번 레이아웃 계산을 하는 것을 방지합니다. 예를 들어, 스크립트에서 여러 요소의 스타일을 변경할 때, 가능한 한 일괄적으로 변경사항을 적용하여 레이아웃 계산을 한 번만 하도록 합니다.
- avoid animating box model properties? => 박스 모델 속성을 애니메이팅하는 것을 피하세요?
- CSS의 박스 모델 속성(예: width, height, margin, padding 등)을 애니메이션하면 레이아웃 변화를 유발하여 브라우저가 레이아웃을 재계산해야 합니다. 이는 성능 저하를 초래할 수 있습니다.
- 대신 transform과 opacity와 같은 속성을 사용하여 애니메이션하는 것이 성능에 더 적은 영향을 미칩니다. 이러한 속성들은 레이아웃 계산을 필요로 하지 않으며, GPU 가속도 가능하기 때문에 더 부드러운 애니메이션을 제공할 수 있습니다.
- batch updates? => 업데이트를 일괄 처리?
[5] Paint
- Once the render tree is created and layout occurs, the pixels can be painted to the screen.
- On load, the entire screen is painted.
- After that, only impacted areas of the screen will be repainted, as browsers are optimized to repaint the minimum area required.
- Paint time depends on what kind of updates are being applied to the render tree.
Optimizing for CRP
Improve page load speed by
- prioritizing which resources get loaded,
- controlling the order in which they are loaded, and
- reducing the file sizes of those resources.
Performance tips include
- 1) minimizing the number of critical resources by deferring non-critical ones' download, marking them as async, or eliminating them altogether,
- 2) optimizing the number of requests required along with the file size of each request, and
- 3) optimizing the order in which critical resources are loaded by prioritizing the downloading of critical assets, thereby shortening the critical path length.
[정리] 웹 페이지 로딩 속도를 개선하기 위한 핵심 CRP 최적화 전략
1. 리소스 우선순위 설정 :
필수적인 리소스를 먼저 로드하고, 비중요 리소스의 로드를 연기하거나 비동기로 처리합니다.
2. 리소스 크기 최소화 :
파일 크기를 줄이기 위해 이미지 최적화, 코드 압축 및 최소화를 수행합니다.
3. 요청 수 최적화 :
필요한 HTTP 요청의 수를 최소화하여 네트워크 통신 비용을 줄입니다.
4. 중요 자원의 로드 순서 최적화 :
페이지 렌더링에 필수적인 자원을 우선적으로 로드하여 CRP 길이를 단축시킵니다.
https://developer.mozilla.org/en-US/docs/Web/Performance/Critical_rendering_path
Critical rendering path - Web performance | MDN
The Critical Rendering Path is the sequence of steps the browser goes through to convert the HTML, CSS, and JavaScript into pixels on the screen. Optimizing the critical render path improves render performance. The critical rendering path includes the Docu
developer.mozilla.org
'프론트엔드 > 기본 프론트 지식들 모음' 카테고리의 다른 글
[WHY] 프론트엔드 개발자가 왜 네트워크 관련 지식을 알아야 할까? (1) | 2024.02.27 |
---|---|
Event Loop (1) | 2024.02.27 |
크롬에 'https://www.google.com' 이라고 주소를 적고 엔터를 치면? (1) | 2024.02.27 |
코드를 짜면서 항상 기억해야할 원칙들 (0) | 2023.09.28 |
eslint & prettier (차이 및 작동방법 등) (0) | 2022.07.06 |
댓글