3 min read

Critical and Inlined CSS

When styling pages with CSS, there are various ways to do so - some are adding an attribute to html elements, with <style> tags, or by using imports. My previous website primarily drew from separate .css files, and I used nunjucks to pull them together and permalink them as bundle.css. This lets me divide my css code into sections that reflect my site’s subdivisions, which makes it easy to refer back to and edit. Then, the css bundle is simply added to the layout that I want to use it with. Any pages that use that layout as a template will then have the styling applied.

So what is critical CSS? Critical CSS refers to the styling necessary to correctly render the elements that appear on the initial screen of the site being viewed. The concept of critical CSS can be used to improve loading times; for example, instead of loading all of the styling for a page before delivering it, the styling necessary to format the menu, a heading, etc can be served and then the rest of the styling for objects only visible when the user scrolls can be loaded after asynchronously.

Depending on the page and how much CSS is applied, this can drastically reduce the amount of time that an end user is watching a blank screen.

Inlining CSS refers to embedding CSS in the page (html or otherwise) so that it is included in the source instead of being imported from elsewhere. This is a strategy that can be applied to rendering critical CSS.

On that site, each blog post has the CSS that applies specifically to a blog post inlined. This CSS is not included in the bundle. For this case, I can apply just the CSS necessary to certain pages. For example, there’s no need for a project page to include the styling for a blog post where it wouldn’t contain the elements referenced by the classes. This keeps the footprint small and also can more clearly define each page by not including superfluous styling for that page.

I leveraged 11ty for the implementation. In the layout that each blog post uses, I set a variable, css, to include the styling from the file that contains the post CSS. Then in a style tag, I place the code and minify it with a javascript filter. This allows for abstraction of the logic and ensures there’s just one file that needs to be updated should I change my mind. I currently use inlining less for the speed improvement (minimal, as there’s not very much to load in the first place) and more for the bonus that I can segment and organize even more of my codebase for maximum maintainability.