8

How to load a CSS file async

 3 years ago
source link: http://www.js-craft.io/blog/how-to-load-a-css-file-async/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.

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

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.

Newsletter subscribe:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK