Inline CSS

Inline CSS

As much as I have strong opinions about front end JavaScript development, I am totally lost when it comes to CSS. That is not to say I don’t understand CSS. I do. In fact, I have probably tried every CSS framework and technology under the sun.

LESS, Sass, JS-in-CSS, Flexbox, etc., etc.

At the end of the day, while I understand all of these and can use them, I don’t actually like any of them. I have always wanted something that looks and feels like JavaScript or (even better) is just part of the JavaScript language. You may think that naturally means one of the JS-in-CSS libraries, but…none of the current generation of libraries fulfills the promise (yet).

So, for now at least I file away pretty much all style related work as a hack. With that in mind, I want to share one hack that has been pretty useful for us at GetHuman. Namely, the use of generated inline CSS for increased initial load performance. The way it works is like this:

  1. At build time in a non-production environment, use Addy Osmani’s critical library to generate inline CSS for each route
  2. In production, have your server side page look to see if an inline CSS file exists for that template.
  3. If it does, stick the inline css directly into the server view and lazy load the rest of the CSS using loadCSS.
  4. If there is no inline CSS, then just have a CSS tag in the header for the main CSS file like you normally would.

By doing this, the page can render lightning fast without waiting for any CSS file at all to download. The main CSS file loads in the background.