Advanced Front End Developer Essentials - Part 2
Tags: react, javascript, career, webdev
Published: 2021-10-17 03:31:00

This post is a continuation of [Advanced Front End Developer , Interview Essentials - Part 1](https://dev.to/gouthamjm/advanced-fe-dev-interview-essentials-1-45ho) ,if you haven't read it I strongly recommend you to go through the post where I have explained the CRP in detail


Optimizing the Critical Rendering Path is very essential for performance of a site , and always keep in mind the below rule

> You cannot optimize something that you cannot measure

## 1.DOM Optimization

You should stream HTML as fast as you can ,we can achieve that by these step's minification,compression and caching the HTML.

**In which stage of CRP, Do you think will the page be rendered ?** 
It will be rendered when the render tree is constructed ,i.e. just after CSSOM has been constructed, and it will be the render blocking step , so it becomes crucial to optimize CSSOM


## 2.CSSOM Optimization

As CSS is a render blocking resource,always keep your CSS lean, deliver it as quickly as possible, and we can use media types and queries to unblock rendering

If we have some CSS styles that are only used under certain conditions, for example, when the page is being printed or being projected onto a large monitor,but you are viewing in a mobile ,then we can block rendering on the resources that are not used.

CSS `media types` and `media queries` allow us to address these use cases,in the below example if we maintain a separate style sheet for different use cases , *Example* : we may need to apply certain styling for print or in responsive site we can mention a specific width during which case only the style sheet must be imported

```html
<link href="style.css" rel="stylesheet">
<link href="print.css" rel="stylesheet" media="print">
<link href="other.css" rel="stylesheet" media="(min-width: 40em)">
```

When declaring your style sheet assets, pay close attention to the media type and queries; they greatly impact critical rendering path performance

### Explanation:

```html
<link href="style.css"    rel="stylesheet">
<link href="style.css"    rel="stylesheet" media="all">
<link href="portrait.css" rel="stylesheet" media="orientation:portrait">
<link href="print.css"    rel="stylesheet" media="print">
```

- The first declaration is render blocking and matches in all conditions.
- The second declaration is also render blocking: "all" is the default type, so if you don’t specify any type, it’s implicitly set to "all". Hence, the first and second declarations are actually equivalent.
- The third declaration has a dynamic media query, which is evaluated when the page is loaded. Depending on the orientation of the device while the page is loading, portrait.css may or may not be render blocking.
- The last declaration is only applied when the page is being printed, so it is not render blocking when the page is first loaded in the browser.

### Avoid CSS imports

The CSS import (`@import`) directive enables one stylesheet to import rules from another stylesheet file. However, avoid these directives because they introduce additional roundtrips into the critical path: the imported CSS resources are discovered only after the CSS stylesheet with the `@import` rule itself is received and parsed.

### Put CSS in the document head

Specify all CSS resources as early as possible within the HTML document so that the browser can discover the `<link>` tags and dispatch the request for the CSS as soon as possible.


## 3. JS Optimization

JavaScript allows us to modify just about every aspect of the page: content, styling, and its response to user interaction . JavaScript can also block DOM construction and delay when the page is rendered. To deliver optimal performance, make your JavaScript async and eliminate any unnecessary JavaScript from the critical rendering path

By default, JavaScript execution is "parser blocking": when the browser encounters a script in the document it must pause DOM construction, hand over control to the JavaScript runtime, and let the script execute before proceeding with DOM construction.

**Problem:**

Let's take the below example where there is a style sheet as well as script that modify the  `<p>` tag , so will the text be rendered black or red , the answer to this lies in the order of the execution 
1. Page requests for HTML, and it will start building the DOM
2. Then it will encounter style and request for CSS resources ,during this time CSS doesn't know whether the script will modify the CSS, so it will wait for  CSSOM to be constructed
3. After CSSOM is constructed, then JS will be executed and will build the Render Tree

CSS blocks script as well as rendering page, so it becomes crucial  to optimize the CSS

![JS Optimization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ofq4xmg7o9zfdbyjf6n1.png)

**Solution :** 

1.All JS code might not modify the DOM in such cases one way we can optimize JS it to load it after DOM has been loaded ,like below
```jsx
   <script>
      function loadFunction() {
        alert("Window is loaded");
      }
      window.onload = loadFunction();
    </script>
```
2.Another way to solve this is to add `async` attribute to the  `script` tag , it does two things - it doesn't block DOM construction, and CSSOM construction , so basically what it does is it will allow JS not to block CRP 
3.There is also a `defer` attribute that you can add to the script tag that tells the parser that the script should wait to execute until after the document is loaded

## Summary:

So let's see what all the options we have to optimize the CRP

1. Minification,Compression and Caching - HTML,CSS and JS

2. Reduce critical resources  - CSS media query ,avoid imports and use critical inline CSS , JS - with async or defer attribute

3. Shorten CRP length , i.e. reduce the number of round trips for fetching resources , there are a ton of ways to optimize it based on different communication protocol,You can refer it [here](https://hpbn.co/) 

4. Optimize the order in which the remaining critical resources are loaded: download all critical assets as early as possible to shorten the critical path length.

There are other methods of optimizing a site ,in my next post I will discuss on how to achieve Fast Load time for your site


***References:***


- [https://developers.google.com/web/fundamentals/performance/critical-rendering-path](https://developers.google.com/web/fundamentals/performance/critical-rendering-path)
- [https://classroom.udacity.com/courses/ud884](https://classroom.udacity.com/courses/ud884)