Importance of Refactoring CSS

Optimizing Size And Performance (Tips and Tricks)

By
  • Damini Sinha
May 16 20235 min. read time
refactoring_1280x720.png

Refactoring is the process of restructuring code, while not changing its original functionality. The goal of refactoring is to improve internal code by making many small changes without altering the code's external behavior.

What are the benefits of refactoring?

Refactoring can provide the following benefits:

  • Makes the code easier to understand and read because the goal is to simplify code and reduce complexities.
  • Help in removing duplicate code, by making the scope of functionality more modular.
  • Improves maintainability and makes it easier to spot bugs.
  • Encourages a more in-depth understanding of code. Developers have to think further about how their code will mix with code already in the code base.
  • Focus remains only on functionality. Not changing the code's original functionality ensures the original project does not lose scope.
  • Getting more conssitency in code base.
  • Reducing the large files sizes, hence improving performance.

In worst-case scenarios, all aforementioned issues combined can result in a large CSS file size, even with the CSS minification applied. This CSS is usually render-blocking, so the browser won’t even render the website content until it has finished downloading and parsing the CSS file, resulting in a poor UX and performance on slower or unreliable networks.

How to audit CSS Codebase Health?

Audit can help us understand the current issues and set the guidelines to improve CSS codebase’s health.

It’s also important to establish rules and internal CSS standards within a team or even for the whole company. Clearly defined company-wide standards, code style, and principles can yield many benefits such as:​

  1. Unified and consistent code style and quality​
  2. Easier to understand, robust codebase​
  3. Streamlined project onboarding​

Standardized code reviews that can be done by any team member, not just the lead frontend developer or the more experienced developers.​

When doing a CSS audit or preparing for a CSS refactor, I rely on several of many useful tools to get a general overview and useful stats about the CSS codebase​

  • CSS Stats

A free tool that provides a useful overview of the CSS codebase quality with lots of useful metrics that can help developers catch some hard-to-spot issues.​

CSS codebase and used the metrics from CSS Stats to set some concrete, measurable goals like reducing specificity and reducing the number of color variations. In just three weeks, they’ve managed to improve the overall health of the CSS codebase, reduce the CSS file size, improve render performance on mobile, etc.

css_stats__1_1260x720.png

CSS stats report example

  • Wallace

CLI tools but useful CSS stats and overview which can be used to identify issues related to file size, number of rules and selectors, selector types and complexity, etc.​

also offers a free analyzer tool on the Project Wallace Website which uses a seemingly more advanced version of Wallace in the backend to provide some useful data visualizations and few more metrics that are not available in the Wallace CLI.​

wallace 750 500.png

Wallace report

  • DevTools CSS Auditing

It provides an overview of media queries, colors and font declarations, but also highlights unused declarations which you can safely remove.​

Css_auditing_1_1500x822.png

CSS auditing report

  • CSS coverage
    returns an overview of unused CSS on a page. The Coverage tab in Chrome DevTools can help you find unused JavaScript and CSS code. Removing unused code can speed up your page load and save your mobile users cellular data.

More tools-

Optimizing Size And Performance

CSS optimization and minification -Tools like cssnano and clean-css are among my favorite tools when it comes to CSS optimization and minification. They offer a wide variety of customization options to further control how code is being optimized and which browsers are supported.

Optimizing media queries-

Let’s consider the following example of an unoptimized CSS codebase​

As you can see, we have a repeated @media (min-width: 768px) per component for better readability and maintenance. Let’s run the optimization and minification on this code example and see what we get.​

we can nest multiple selectors under a single media query, so why didn’t the minifier removed the duplicated expression? There is a simple reason for that.

.page {
  display: grid;
  grid-gap: 16px;
}
@media (min-width: 768px) {
  .page {
    grid-template-columns: 268px auto;
    grid-gap: 24px;
  }
}
.products-• grid {
  display: grid;
  grid-template-columns: repeat (2, 1fr);
  grid-gap: 16px;
}
@media (min-width: 768px) {
  .products-grid {
    grid-template-columns: repeat (3, 1fr);
    grid-gap: 20px;
  }
}
Media queries inside every class
.page{display:grid;grid-gap: 16px}@media (min-width: 768px)
{.page{grid-template-columns:268px auto;grid-gap:24px}}.products- 
grid{display:grid;grid-template-columns: repeat (2,1fr) ;grid-gap:16px}@media
(min-width: 768px){.products-grid{grid-template-columns: repeat (3, 1fr);
grid-gap:20px}}
Minified version of above CSS class with duplicated media queries
  • Rule order matters in CSS so to merge the duplicated media queries, code blocks need to be moved. Tools and packages like postcss-sort-media-queries allow us to remove duplicated media queries and further reduce the file size.​
  • Removing unused CSS tools like purgecss go through all the files in the project and use all the classes mentioned in files as selector

Eliminating render-blocking

CSS By default, CSS is a render-blocking resource, meaning that the website won’t be displayed to the user until all linked stylesheets and their dependencies (fonts, for example) have been downloaded and parsed by the browser. we can draw even more conclusions from the Web Vitals charts. By taking a look a the Largest Contentful Paint (LCP) chart, we can get a detailed overview of render-blocking resources and how much they affect the initial render.​

Some tips could be -​

  • Splitting and conditionally loading stylesheets with media queries​
  • Deferring stylesheets ​
  • Critical css - website loads with the minimum amount of styles which are guaranteed to be used on the page when it’s initially rendered.​
  • Deferring font files and stylesheets - Font files also add quite a bit of overhead to the initial render performance.​
Eleminate rendering block.png

Example of Eliminating rendering block

Server-Side Optimizations​

Http compression

In addition to minification and file-size optimization, static assets like HTML, CSS files, JavaScript files, etc. HTTP compression algorithms like Gzip and Brotli can be used to additionally reduce the downloaded file size.​

Caching stylesheets ​

Caching static files is a useful optimization strategy. Browsers will still have to download the static files from the server on the first load, but once they get cached they’ll be loaded from it directly on subsequent requests, speeding up the loading process.​

Cdn or self-hosting

Content Delivery Network (CDN) is a group of geographically distributed servers that are commonly used for the reliable and fast delivery of static assets like images, videos, HTML files, CSS files, JavaScript files, etc.​

Auditing CSS File Size And Performance

WebPageTest is one of performance auditing tools which can be used to get a detailed overview of the website loading process, render-blocking resources, etc.

webtest.png

Auditing CSS files report

These are some tips and tricks which can help in reduction of duplicate CSS styles, thus improving website performace.

Disclaimer: The views and opinions expressed in this article are those of the author and do not necessarily reflect the official policy or position of DNB.

© DNB

To dnb.no

Informasjonskapsler

DNB samler inn og analyserer data om din brukeratferd på våre nettsider.