Inlining CSS is a common practice for optimizing the critical rendering path(opens in a new window). Once you've analyzed and factored out styles blocking rendering, you'll likely want build time enhancements provided by tooling like PostCSS, before inlining.
Eleventy shortcode #
Eleventy can extend the static site generation with definitions for reusable content. You can utilize this capability to generate your web's critical path CSS. Configure 11ty with an universal template shortcode(opens in a new window)for processing render blocking styles.
PostCSS shortcode #
jseleventyConfig.addPairedShortcode("postcss",
async code => {
// for relative path CSS imports
const filepath = path.join(
__dirname,
"src/_includes/critical-path.css");
return await postcss([
// PostCSS plugins
require("postcss-import"),
require("precss"),
require("autoprefixer"),
require("cssnano")
]).process(
code,
{ from: filepath })
.then(result => result.css);
});
The above shortcode configures PostCSS to process files imported to an entry point, for which vendor prefix are generated, and finally minified.
Inline styles #
The shortcode is available to be referenced in a page layout, and fed the critical rendering path CSS. An entry file is specified, which in turn enables inlining of required component styles with the @import
directive.
Shortcode in page layout #
liquid<html>
<head>
<!-- ... -->
<style>
{% postcss %}
{% include critical-path.css %}
{% endpostcss %}
</style>
</head>
<!-- ... -->
</html>
Template shortcodes can be used for definitions of styles for specific pages or for inlining all CSS. What granularity you aim for, mostly becomes a matter of prioritizing maintainability or performance requirements.