Skip to content

Instantly share code, notes, and snippets.

@justmarkup
Last active February 17, 2016 07:43
Show Gist options
  • Save justmarkup/8ace46cf4198d4a37f17 to your computer and use it in GitHub Desktop.
Save justmarkup/8ace46cf4198d4a37f17 to your computer and use it in GitHub Desktop.
CSS loading

Thoughts about a way to progressive enhance the technique to control CSS loading by Jake Archibald.

My idea was to set a class for html (which gets changed if custom properties are supported) and in the CSS use:

.no-ccp footer {
  display: block;
}

footer {
  display: var(--footer-blocker, block);
}

This way if the browser supports custom properties the CSS loads progressively, if not the content will still be visible but probably loaded out-of-order.

So, I guess using loadCSS or similiar is better at the moment if you want to load/show CSS in order.

Code

<html class="no-ccp">
...
<!-- not sure if this really doesn't load if rel is not set but my sporadic tests shows so, probably not working in some browsers -->
<link id="style" href="all-combined.css">
  <script>
  if ('visibilityState' in document) {
    if (window.CSS && window.CSS.supports && window.CSS.supports('--a', 0)) {
      // spwap no-ccp class to yes-ccp class to load parts async if custom properties are supported
      document.documentElement.className = document.documentElement.className.replace(/\bno-ccp\b/,'yes-ccp');
    }
    // load CSS files
    [
    'main-content.css', 
    'about-me.css', 
    'comments.css', 
    'footer.css'].map(function (url, i) {
      var link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = url;
      document.head.appendChild(link);
    });
  } else {
    // load the combined styles all in once
    window.onload = function () {
      document.getElementById('style').rel = 'stylesheet';
    }
  }
  </script>
  <noscript>
    <!-- as a fallback if user has JavaScript disabled load all combined CSS-->
    <link rel="stylesheet" href="all-combined.css">
  </noscript>

Demo: https://justmarkup.com/demos/async-css/index1.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment