Loading Styles Asynchronously

You can easily load CSS asynchronously by changing the media to print and adding a dash of JavaScript.

July 23, 2019

Until recently, when you’ve wanted to load a CSS file asynchronously, the best method was using a preload polyfill like LoadCSS. But according to Scott Jehl, recent browsers have standardized CSS loading behavior and enabled an option that just requires a little bit of JavaScript in your CSS <link>.

<link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'">

Setting the media attribute to print loads the stylesheet without delaying the page render (since the user isn’t trying to print immediately). The onload script then sets the media to all after the file has finished loading. And voilà, the page has the deferred styles without having to load a separate script file.

See the inspiration