How Browser Process Styles

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuchuji/article/details/81661210

We all know that when scripts are executing the browser will halt the parsing process (thus stop the rendering process), but it’s not that clear for styles. Here we are going to dive deep into how styles are interpreted in browsers

First of all we give an overview of the main flow of how browser process a page with html, scripts and styles, and what role styles play inside.

Webkit main flow

CSS styles will be parsed to CSS rules and constructed CSSOM (CSS Object Model), which will be finally combined with DOM tree to construct the render tree. And the render tree, is finally layout and painted, displayed on the screen.

Since we could add styles in three ways: inline css, css rules inside <style> tag and external css files with a <link> tag. For the former two ways, css rules is parsed and applied when they are reached, which’s clear. But for the last one, the situations are quite different when putting <link> inside <head> and <body>.

If putting <link> inside <head>, browser will halt the layouting and painting process and start to download and parse the css files first when it encounters the <link>. Thus the browser will display a blank page and it also delay the first paint(FP). Therefore, many analysis and optimizing tools recommend eliminating render-blocking css, which are useless styles for rendering content above the fold so that speeding up the FP time. This is also what W3C recommends of.

But it’s completely different when putting <link> inside <body>. When browser encounters a <link> tag, it will continue to parse and render the following content, leading to a broken page if some styles are necessary for the following rendering. This is implemented by browser venders and not specified in W3C (to be clarified).

Let’s go back to styles optimization, eliminating render-blocking css. To achive the goal, we could not link to a large css file, which definitely makes it slow. The way today’s packaging tools (like webpack) working out, is to split the code into extra chunks, which are loaded and add to the <head> on demand. This is the feature called code spliting.

猜你喜欢

转载自blog.csdn.net/zhuchuji/article/details/81661210