Use cases of embedded CSS

Let’s talk about the cases where it makes sense to place your CSS within the head of your HTML.

Mostly one can say that micro sites or single page applications are perfect for this technique since users don’t visit more than one page of your application — they stay on the same page for all of their visit and thus don’t need the advantage of client-side caching – up to a certain extend. This becomes a negative example if you have high traffic from returning visitors.

Another use case are pages that need to be served very very fast as for example home pages or landing pages. You want to avoid the Critical Rendering Path in this case more than in others. Users will wait a few more seconds if you got their attention in the first place.

How to do inlining

This section is only important if you are really really sure you want to embed your CSS in the HTML head. As per my own front-end workflow here is an example on how to integrate this feature with a Grunt build-flow.

There are a couple of Grunt modules out there that do this kind of task and nothing more. For example grunt-inline-css which is basically targeted at HTML mailings but can be easily used for embedded CSS on any web project. Done!

The configuration is easy and an example can be found within the README file of the repo.

Another alternative would be to read the content from a generated minified CSS file with Node’s `fs` API and than use grunt-replace within your build workflow. Also straightforward if you are used to Grunt.

Alternatives

One more thing though: Combined with other techniques to save loading time the idea of inlining CSS in the HTML head might be a good solution.

If you load the content of your “classic” website asynchronously you can leave out the head and scripts for new pages which makes loading pages faster in general but introduces a couple of other problems you have to work around (ie. browser history). There are services optimized for this kind of task. You get the idea…

Apart from that there are several techniques which combine some of the ideas together. I don’t want to go into detail.