šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Deferred loading for CSS scripts

CSS is render-blocking. This means the while browser is downloading the CSS, it stops painting the page thus impacting performance.

Therefore any CSS that is not critical to the above-the-fold content is a good candidate for deferred loading.

In order to do a deferred loading for a CSS file we can use the below code:

<link href="my-styles.css" as="style" rel="preload"  
    onload="this.onload=null;this.rel='stylesheet'">

We can maximieze the performance by splitting our CSS into:

  • critical CSS
  • and non-critical CSS.

Loading the critical CSS

The styles that are required to show the immediate content needed for the above the fold section are considered critical CSS.

The best place to put the critical CSS is directly in the head of our page using the style tag:

<head>
  <style type="text/css">
    header { /* ....  */ }
    .logo { /* ....  */ }
  </style>
</head>

If you place the critical CSS in its own file remember that the size of a single roundtrip HTTP is 14kb so it would be great to keep the size of the file under this amount.

Deferred loading for non-critical CSS

Any CSS styles that are not used for the initial rendering can be downloaded later with deferred loading:

<link href="non-critical.css" as="style" rel="preload"  
    onload="this.onload=null;this.rel='stylesheet'">

Some notes on the above code:

  • the as attribute represents the type of content retrieved by the <link> tag
  • we set rel="preload" so that the browser knows to load the resources as soon as they are required for the rendering of the page
  • after the non-critical.css file is downloaded we set onload="this.onload=null;this.rel='stylesheet'" to avoid repeated calling and change the 'rel' attribute value to a stylesheet
  • in order to provide a fallback if the Javascript is not executed we can use the noscript tag:
<noscript>
    <link rel="stylesheet" href="non-critical.css">
</noscript>

Hope that this will help the performance of your web page. Rember that you can also defer the loading of the Javascript files.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *