🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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."

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