Performance Optimization Using Css

Performance Optimization Using Css

Understanding CSS rendering and performance optimization

CSS(Cascading Style Sheets), which is usually known for its magic to create beautiful web pages, may land you in trouble by messing up the user experience due to poor web performance. In this blog, we'll cover the ways to optimize web performance using CSS.

Why does web performance matter?

Performance plays a major role in the success of any online venture. Sites with a faster loading speed and smooth user interaction attract more users, which in turn results in higher conversions, a positive impact on SEO, and most importantly improves the user experience.

Web performance is all about making websites fast, including making slow processes seem fast.

How browsers render HTML and CSS?

Before, diving deep into how we can optimize our CSS code for better performance, let us first understand how HTML and CSS are rendered in our browsers.

Render Tree.png

  • The browser first loads the HTML(received from the server).
  • It then parses the HTML and initiates requests every time it finds external resources like stylesheets, scripts, etc.
  • Some requests are blocking, which means the parsing of HTML is halted until all the resources are handled.
  • Then the HTML parsing and building of DOM continues, at the end of which browser constructs the CSS object model.
  • Once the DOM and CSSOM are completely built, the browser builds the render tree and prepares the layout based on the screen size and calculated styles.
  • The visual display of the page is then shown on the screen (this stage is called painting).

How does CSS impact web performance?

Linking of CSS with a traditional link tag(with rel="stylesheet")is synchronous and render-blocking, which means that the browser can paint the screen only when the complete CSS is downloaded and the object model is built. Page loading speed can be improvised by reducing the loading and parsing time of HTML and CSS.

Ways to optimize web performance using CSS

Media attribute and queries

Media queries can be used to optimize the critical rendering path by splitting the code into multiple files based on media queries.

<link rel="stylesheet" href="styles.css"> <!-- blocking -->
<link rel="stylesheet" href="print.css" media="print"> <!-- not blocking -->
<link rel="stylesheet" href="mobile.css" media="screen and (max-width: 480px)"> <!-- not blocking on large screens -->

credit: MDN Web Docs

Minify CSS

Minification is using short hands, removing all the unused and repetitive styles, removing extra whitespaces, and comments.

Use simple selectors

The longer the selectors, the more will be the work for the browser to parse. More number of selectors will ultimately increase the overall size of the stylesheet, which in turn will increase the loading time.

Avoid excessive animations

Animations can be used for a better user experience. But, overdoing animations will add to the parsing time, which will ultimately slow down the browser.

Avoid use of import statements

@import statement allows you to add external styles and fonts inside other CSS files. This impacts the web page speed as it loads each external file, before processing the rest of the CSS code.

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap');

To overcome this, we can use link tags in the head of our HTML code or combine all external files into a single file and then call the CSS file using import statement.

<link rel="preload" as="font" href="https://fonts.googleapis.com/css?family=Open+Sans">

Here, the rel="preload" and as="font" tell the browser to start downloading the font as soon as possible.

Get rid of inline CSS

Though using inline CSS reduces the load and parsing time of CSS files, it, in turn, increases the HTML payload. It may also result in code repetition as a result of not using classes for common styles.

Using will-change property

will-change property helps the browser to know which properties or elements are going to be changed. This enables browser to set up optimizations before the element/property is actually changed.

.element{
   will-change: opacity, transform;
}

Using font-display property

font-face property is applied to the @font-face rule. It defines how font files are loaded and displayed by the browser. This improves performance by making the text visible instead of having a blank screen, with a trade-off being a flash of un-styled text.

@font-face {
  font-family: someFont;
  src: url(/path/to/fonts/someFont.woff) format('woff');
  font-weight: 400;
  font-style: normal;
  font-display: fallback;
}

credit: MDN Web Docs

Optimize images

Large and high-resolution images can jam the rendering process. Using slightly compressed images can save a lot of file size without compromising much on the quality of the image.

Caching and compressing stylesheets

Caching of CSS yields better performance as it can be reused for every page request post the initial request. Using CDNs helps in improving the delivery time of assets.

Compressing the stylesheets before sending the to the browser reduces the transfer time as a result of reduced file size.

How to measure web performance?

The following tools help in identifying styling bottlenecks in the code.

DevTools Network Panel

image.png

Any long bar is a cause of concern. One should be especially concerned about the long blocked bars shown in white color. It indicates that the downloading of the subsequent requests cannot be completed until the render-blocking CSS and JavaScript files are processed at the top of the HTML page.

Chrome DevTools Lighthouse Panel

Lighthouse can be used to generate Performance, Progressive Web App, Best Practices, Accessibility, and Search Engine Optimization reports for mobile and desktop devices. It also suggests improvements that can be done to optimize the mentioned parameters.

ezgif.com-gif-maker.png

Chrome DevTools Coverage Panel

CSS and JavaScript assets are shown in the Coverage panel, with the proportion of unused code in red.

ezgif.com-gif-maker (1).png

Note: The unused code metric will only decrease if you’re browsing a Single Page Application that loads content without a page refresh.

Conclusion

Performance matters to users. Web developers need to build apps that react quickly and render smoothly.

To summarize, web performance can be improved by:

  1. Optimizing CSSOM construction
  2. Removing unnecessary styles
  3. Minifying or compressing the CSS files
  4. Splitting CSS code into multiple files based on media queries to avoid render blocking.
  5. Optimizing images
  6. Caching and compressing CSS files

All the practices might not have a major impact individually but when combined, they might add up to a significant number.

For more insights, you may refer to: