📜 ⬆️ ⬇️

Optimizing web page performance: CSS

Nowadays, Internet speed is quite high. It would seem that you can forget about those times when we had to wait 20-30 (or even more) seconds for the web page to load and display on the screen - now we are waiting for the page to be drawn on average for about one or two seconds. However, you should not forget that a significant part of users access your site from mobile devices, on which the connection is not always stable. In this regard, it will not be superfluous to pay a little attention to optimizing your code.

This article focuses on various methods of optimizing style sheets. I will talk about what affects the speed of page rendering, how to make the browser render the page faster and what tools to use for optimization.

How the page is displayed


Let's understand what happens when you open a new page.
')
So, you press enter and the browser sends a request to the server. In response, the server sends the requested page.

  1. The browser analyzes the resulting markup. Nodes are formed, from which the DOM is then built.
  2. If the browser detects references to style sheets, it immediately sends a request to the server and downloads the files; at the same time page rendering is blocked.
  3. After loading the styles, the browser analyzes them and builds CSSOM.
  4. When the DOM and CSSOM are formed, the browser creates a rendering tree based on them. Only those elements that will be displayed on the screen fall into it.
  5. For each element of the visualization model, its position on the page is calculated. This process is called layout design .
  6. After the completion of the layout, the browser renders the result (painting).

You can tell a lot about the page rendering process, but in the context of this article we are interested in the second paragraph.

To begin with, I repeat: the browser blocks page rendering during loading and processing of style sheets. If there are several css-files connected to the page, the browser will load everything, regardless of media queries. Fortunately, modern browsers are smart enough to first download the files that are directly required to render the main part of the page. Let's consider the following example:

<link href="style.css"> <link href="style.css" media="screen"> <link href="style.css" media="(orientation: portrait)"> <link href="style.css" media="(max-width: 960px)"> <link href="style.css" media="print"> 

The link to the first style sheet file has no attributes, and the browser will start downloading the file immediately after finding the link to it. The link to the second file has the attribute media="screen" . This attribute the browser assigns to the <link> element by default if it is missing, so the second file will be processed immediately after the first. Links to the third and fourth files contain a conditional media query. If this condition is met, the browser will begin processing the file. If it is not executed, the browser will postpone these files “for later”, and will first process more actual styles. In the fourth link in the media attribute is the value "print", indicating to the browser that this file contains styles for printing. Since they are not currently required by the browser, it will also postpone their processing.

Optimization methods


With the order of processing styles, we figured out, now it's up to you to adopt this. Next, we will talk about how to optimize the stages of page rendering (loading, processing styles).

Using high performance selectors


Do not forget that different selectors are processed by the browser at different speeds. Steve Sauders conducted research and sorted CSS selectors by performance from the fastest to the slowest:


It is not recommended to use the general selector * for anything. By the way, the gain when using an identifier instead of a class is actually quite small, so you can use what is more convenient for you.

Cascade reduction


Large cascade adversely affects performance. Compare two designs:

 #header .header__inner nav ul.nav-menu li:hover a {} #header li:hover a {} 

Obviously, the second construct will be processed faster.

I can not mention one important point. The browser handles selectors from right to left. Consider the following construction:

 .social li a {} 

In this case, the browser will first find all the links on the page (just imagine how long it takes to process such a request on huge pages), then select the links nested in <li> , from the received links it will drop everything that is not nested in the element with the class .social . I recommend in such cases to reduce the design to two selectors of the following form:

 .social .social_link {} 


This approach is better because we reduced the cascade to a minimum and replaced the selectors with more efficient ones.

CSS minification and bonding


Avoid using a lot of small CSS files; good practice is to “glue” all the files. Thanks to the file splicing, the browser will have to make one request to the server instead of several.

Also do not forget about file minification. Typically, the code is a lot of garbage in the form of comments (do not throw tomatoes, this is rubbish for the browser, not for the developer). There are many different tools for compressing and minifying style sheets. I will give some of them:


Disable: hover states when scrolling the page


Some sites are replete with interactive elements that have unique: hover-states. When the user scrolls the page, he is hardly interested in what will happen if you hover the cursor over that button or this input field. You can safely turn off: hover-state when scrolling.

A simple solution is to create a .disable-hover class and add it to <body> while scrolling.

 .disable-hover { pointer-events: none; } 

 var body = document.body, timer; window.addEventListener('scroll', function() { clearTimeout(timer); if(!body.classList.contains('disable-hover')) { body.classList.add('disable-hover') } timer = setTimeout(function(){ body.classList.remove('disable-hover') }, 500); }, false); 

Critical-path CSS


As you have already learned from the beginning of the article, styles connected via <link> block the page from being drawn until it is fully loaded. If the style sheet has a large size, then users of mobile devices will feel a significant delay before any appearance on the page. In other words, the page will be completely empty until the styles are loaded.

To avoid this, a technique was invented that allows you to display some of the content even before the styles are fully loaded. It is applied as follows. Look at the desktop and mobile versions of the site and determine which parts of the page are critical to the user. Select the CSS that styles these pieces, minify it and place in an in-line view before connecting the main styles. An inline view means a description of styles directly on the page itself, inside the <style> .

For many, finding critical CSS is a tedious task. Fortunately, there have long been tools to automate this process.


Conclusion


Hope this article was helpful to you. I would be glad if in the comments you describe your techniques for optimizing CSS. Thank you for reading!

Source: https://habr.com/ru/post/244815/


All Articles