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

How to load a CSS file async

We can load CSS asynchronously like this:

<link rel="stylesheet" href="style.css" media="print" 
   onload="this.media='all'; this.onload=null;">
When should I use it?

Keep in mind that CSS is render-blocking. Performance-wise this is a problem as the browser is downloading the CSS, it stops painting the page.

Therefore any CSS that is not critical to the above-the-fold content is a good candidate to be loaded async. Also, keep in mind that the 14kb-ish is the size of a single roundtrip HTTP request, so it would be great to keep the critical CSS under this size and defer the loading for the rest of your CSS.

How does it work?

Well, given that we don't have (yet) a native method for loading CSS async we need to use the above workaround. We trick the browser that the media type doesn’t match the current environment, so it will not be render-blocking. After the loading is done, we use the javascript onload event to tell the browser to actually use the deferred CSS.

You can read more about it in this initial article written by Scott Jehl.

Why can I use the link preload attribute to load CSS async?

Yes, you can and it works. Just that it seems that the media="print" approach will give better results. As Scott Jehl explains:

"More importantly though, preload fetches files very early, at the highest priority, potentially deprioritizing other important downloads, and that may be higher priority than you actually need for non-critical CSS."

πŸ“– 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 *