Demystifying the Critical Rendering Path: A Deep Dive into Web Page Loading
Tags: webdev, javascript, html, css
Published: 2023-09-08 17:09:13

🚀When you visit a website, you expect it to load quickly and display content seamlessly. Behind the scenes, the browser goes through a complex process known as the Critical Rendering Path (CRP) to achieve this. Understanding how CRP works is crucial for web developers and designers to optimize web page loading times. In this blog, we'll dissect the CRP, discussing various elements like regular/async/defer attributes, DOM, CSSOM, render tree, layout and paint, incremental and non-incremental parsing of HTML and CSS, and multiple render tree layers due to special tags.

## The Critical Rendering Path (CRP) Unveiled 🚧


![Critical Rendering Path](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4r9vmr4zxiocvd13czt.gif)

### Parsing HTML and CSS 🧩

The journey of a web page begins with the parsing of HTML and CSS files. When the browser encounters an HTML document, it starts parsing it from top to bottom. However, it can be categorized into two types: incremental and non-incremental parsing. 📝

- **Incremental HTML Parsing:** Browsers achieve this by recognizing and parsing the **HTML** in chunks, rather than waiting for the entire document to be parsed. 🔄
- **Non-Incremental CSS Parsing:** Browsers recognize and wait for the entire **CSS** file to be downloaded and then parsing of that file starts. A good practice is to split a large CSS file into multiple smaller ones so that, in a way, incremental parsing can be achieved.🚫

### Building the DOM and CSSOM 🏗️

As the HTML and CSS are parsed, the browser constructs two essential structures: the DOM and the CSSOM. 🏢

- **DOM (Document Object Model):**
  ![DOM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhvttglfhzacl3bovw6x.jpg)
  The DOM represents the hierarchical structure of the web page and its content, allowing JavaScript to access and manipulate the elements. During parsing, the browser creates a DOM tree, which is the foundation for rendering content. 🌲


- **CSSOM (CSS Object Model):**
  ![CSSOM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/km2qmvvs7ggrti4f0zzm.jpg)
  The CSSOM represents the styles and layout information for the web page. It's essential for rendering the page correctly. When parsing CSS, the browser creates a CSSOM, which is later combined with the DOM to produce the render tree. 🎨

### Render Tree Construction 🌌


![Render Tree](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pntovawayrqaj5ii3bl3.gif)

The render tree is a critical step in the CRP as it determines what is displayed on the screen. It's a combination of the DOM and CSSOM, but it excludes elements that are not intended for rendering, such as hidden or off-screen elements. This optimized tree is used to perform layout and paint operations. 🖌️

#### Multiple Render Tree Layers 📦

Some HTML tags and CSS properties introduce multiple render tree layers. For instance: 🏛️

- **iframe**: Iframes create separate browsing contexts, essentially embedding another web page within the main page. Each iframe generates its own render tree layer. This allows for the isolation of content and independent scrolling and interaction within the iframe. 🌐
- **object**: The object element is used for embedding external resources, such as multimedia files or interactive content. Like iframes, it can introduce its own render tree layer. 🎥
- **embed**: Similar to the object element, embed is used for embedding external content like multimedia files. It also creates its own render tree layer. 📺
- **video**: The video element is used for embedding video content in web pages. It creates a separate render tree layer to manage video playback and controls. This allows for seamless video rendering and interaction. 🎬
- **audio**: Similar to the video element, the audio element is used for embedding audio content and generates its own render tree layer for audio playback and controls. 🎵
- **canvas**: The canvas element provides a drawing surface for JavaScript to render graphics and animations. It creates a unique render tree layer for dynamic rendering operations. 🎨
- **svg**: Scalable Vector Graphics (SVG) elements, such as circle, rect, and path, generate their own render tree layers when used for vector-based graphics and animations. 🖼️
- **math**: The math element is used for rendering mathematical equations and formulas using MathML (Mathematical Markup Language). It creates a specific render tree layer for mathematical content. ➗
- **iframe**: Although mentioned earlier, it's worth reiterating that iframes are commonly used for embedding external content and always create their own independent render tree layers. 🌐

These elements introduce complexity to web page rendering, and web developers need to consider their behavior when designing and optimizing web pages. Careful handling of these elements can lead to better performance and user experiences. 🚀🖥️

### Layout and Paint 🖼️

- **Layout:**
  ![Layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qzoauw41gfa0bv5in4e.gif)
  After the render tree is constructed, the browser calculates the layout of each element, determining its position and size on the screen. Layout can be a resource-intensive operation and should be minimized by avoiding layout-thrashing JavaScript code. 📏

- **Paint:**
  ![Paint](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qgdje82prspam29mh95u.gif)
  Once the layout is calculated, the browser proceeds to paint the pixels on the screen, applying colors, images, and styles to the appropriate locations. This process is also known as rasterization. 🎨

### Synchronous, Async, and Defer Attributes 📜

![Synchronous vs Async vs Defer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l6l7t7vemm0c1tvx9sln.jpg)

HTML **script** elements often include attributes like async and defer that affect how JavaScript is loaded and executed. ⚙️

- **Synchronous:**

```html
<script src='./script.js'>
```

Scripts without the async or defer attribute block the HTML parsing process and execute immediately. This can lead to slower page rendering if scripts are placed in the head of the document. 🚀

- **Async:**

```html
<script src='./script.js' async>
```

Scripts with the async attribute are loaded asynchronously while HTML parsing continues. They execute as soon as they're downloaded, which can lead to scripts executing out of order, potentially causing issues. 🏎️

- **Defer:**

```html
<script src='./script.js' defer>
```

Scripts with the defer attribute are also loaded asynchronously, but they execute in the order they appear in the document, after the HTML parsing is complete. This often results in a smoother user experience. 🕰️

### Conclusion 📝

Understanding the Critical Rendering Path is crucial for optimizing web page loading performance. By comprehending the impact of regular/async/defer attributes, DOM, CSSOM, render tree, layout and paint operations, incremental parsing, non-incremental parsing, and the presence of multiple render tree layers due to special tags, web developers can make informed decisions to enhance user experience and page load times. In an increasingly competitive digital landscape, mastering the CRP is a must for creating fast and responsive web applications. 🚀🌐