Hi, my name is Sergey Labozy, and I'm a software engineer at Focus Reactive. Over the past few years, I've spent a lot of time exploring web performance, and in this talk I want to share with you some insights on a key topic. Critical CSS, a powerful way to enhance user experience. In this talk we'll explore what critical CSS is, when to use it or not, how to implement it effectively, and some common challenges and use cases.
Before we jump into critical CSS, let's start at the very beginning. How a browser renders a page. This involves the critical rendering path, a sequence of steps the browser takes to convert HTML, CSS, and JavaScript into visible content on the screen. Let's break it down briefly. First, browser needs to make a request to get initial HTML. As soon as it receives the first HTML chunk, you start building the DOM, document object model. The browser finds the CSS and starts constructing the CSOM, CSS object model. When the DOM and CSOM are ready, the browser combines them into a render tree, which only includes the visible elements. Finally, the layout and paint steps occur and the content appears on the screen.
The main goal here is to render content as quickly as possible, but browsers have limited resources like time and CPU. Time is crucial, because we want the user to see the content as fast as possible, which is measured by a core vital metric called largest content to paint, or LCP. And given that everything happens in the user's browser, CPU usage is equally important, especially for mobile devices. Add to this varying network speeds and latencies. We also should mention JavaScript here. JavaScript can dynamically modify the DOM and CSOM. Manipulating the DOM and CSOM can be very slow. Not necessarily and not in all cases, but we won't go into that here, we just assume that we don't modify the DOM and CSOM with JavaScript.
With understanding of critical rendering path, let's get closer to why critical CSS matters. We've seen that the render tree needs both the DOM and the CSOM. However, unlike the DOM, the CSOM can't be built incrementally. Why? Because CSS is cascading, meaning the order of CSS rules affects their specificity. The last line of CSS could override all preceding styles. This is why the browser can't partially apply CSS. It must first download, parse, and understand the entire stylesheet to avoid flashes of unstyled content. How to Add CSS to HTML? There are two primary ways to add CSS to your HTML. Inline styles using style tags or external stylesheets using link tags.
Comments