Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

How to load a CSS file async

We can load CSS asynchronously like this:

<link rel="stylesheet" href="style.css" media="print" 
   onload="'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.

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

Home Screencasts Best of Newsletter Search X