Load CSS async

Browsers do not have a built-in feature to load stylesheets asynchronously like JavaScript. To achieve this, you can (ab)use preload resource hint.

This example has 2 fallbacks:

Feature detection based on w3c/preload: how to feature detect?


<link rel="preload" href="async.css" as="style" onload="this.rel='stylesheet'">
<noscript class="async-css"><link rel="stylesheet" href="async.css"></noscript>

<script>
function supportsToken(token) {
  return function(relList) {
    if (relList.supports && token) {
      return relList.supports(token)
    }
    return false
  }
}
    
;(function () {
  var supportsPreload = supportsToken("preload")
  var rl = document.createElement("link").relList
  if (!supportsPreload(rl)) {
    var styles = document.getElementsByTagName('noscript')
    for (var i = 0 ; i < styles.length ; i++) {
      if (styles[i].getAttribute('class') === 'async-css') {
        var div = document.createElement('div')
        div.innerHTML = styles[i].innerHTML
        document.body.appendChild(div)
      }
    }
  }
})()
</script>