No matter what website you are building, in today’s world, you’ll have at least some CSS styling on it. Despite this fact, an often overlooked part of web development is CSS performance. Not to worry! There are a few simple tricks you can use to easily improve the speed of your stylesheets.
1. Make sure the files are non-blocking in HTML
Typically, we import a CSS file in our HTML like this:
The problem with this is that it loads the CSS files in a synchronous manner and prevents the rest of the page rendering until the stylesheet has fully loaded. This can be undesirable. Instead, we can preload in the stylesheets which can help prevent render-blocking with a simple keyword:
This tells the browser to fetch these stylesheets early in the page lifecycle before the rest of the page is rendered in — Therefore, helping to prevent any render-blocking that may potentially occur because of late-to-load stylesheets.
2. Move critical CSS styles into an inline stylesheet
The browser will not render a DOM element until all of it’s respective styles have been loaded in. This can be a problem if your elements styles are all stored in a single large stylesheet that takes seconds to load. Instead, we can give the user a better experience by moving all of the critical CSS styles to be inline inside of the HTML file:
This means that we can render all of the critical DOM elements before the rest of the stylesheets have been loaded in. There are several tools that can help you find out what styles are critical and what styles aren’t. One of them is
grunt-critical which can be used in conjunction with
3. Use preconnect to load fonts faster
When a browser requests some fonts it does a DNS lookup, establishes a TCP connection and then asks for the fonts from the server. These steps can cause significant slowdown. Instead we can establish these connections before the browser even knows that it’s going to need to ask for the fonts with the
preconnect option on the
This tells the browser to establish the DNS lookup and TCP connection as soon as the page loads instead of doing them whenever the browser gets to the point in a CSS file where a font lookup is needed.