šŸ“• Build AI Agents using LangGraph.js is now out!

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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