Critters is a plugin that inlines your app's critical CSS and lazy-loads the rest.
It's a little different from other options, because it
doesn't use a headless browser to render content. This tradeoff allows
Critters to be very fast and lightweight. It also means Critters inlines all
CSS rules used by your document, rather than only those needed for
above-the-fold content. For alternatives, see
Similar Libraries.
Critters' design makes it a good fit when inlining critical CSS for
prerendered/SSR'd Single Page Applications. It was developed to be an excellent
compliment to
prerender-loader,
combining to dramatically improve first paint time for most Single Page
Applications.
- Fast - no browser, few dependencies
- Supports preloading and/or inlining critical fonts
- Prunes unused CSS keyframes and media queries
- Removes inlined CSS rules from lazy-loaded stylesheets
First, install Critters as a development dependency:
npm i -D @playform/crittersor
yarn add -D @playform/crittersimport Critters from "@playform/critters";
const critters = new Critters({
// optional configuration (see below)
});
const html = `
<style>
.red { color: red }
.blue { color: blue }
</style>
<div class="blue">I'm Blue</div>
`;
const inlined = await critters.process(html);
console.log(inlined);
// "<style>.blue{color:blue}</style><div class=\"blue\">I'm Blue</div>"That's it! The resultant html will have its critical CSS inlined and the stylesheets lazy-loaded.
All optional. Pass them to new Critters({ ... }).
options
pathStringBase path location of the CSS files (default:'')publicPathStringPublic path of the CSS resources. This prefix is removed from the href (default:'')externalBooleanInline styles from external stylesheets (default:true)inlineThresholdNumberInline external stylesheets smaller than a given size (default:0)minimumExternalSizeNumberIf the non-critical external stylesheet would be below this size, just inline it (default:0)pruneSourceBooleanRemove inlined rules from the external stylesheet (default:false)mergeStylesheetsBooleanMerged inlined stylesheets into a single<style>tag (default:true)additionalStylesheetsArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[String> Glob for matching other stylesheets to be used while looking for critical CSS.reduceInlineStylesBooleanOption indicates if inline styles should be evaluated for critical CSS. By default inline style tags will be evaluated and rewritten to only contain critical CSS. Set it tofalseto skip processing inline styles. (default:true)preloadStringWhichpreload strategyto usenoscriptFallbackBooleanAdd<noscript>fallback to JS-based strategiesinlineFontsBooleanInline critical font-face rules (default:false)preloadFontsBooleanPreloads critical fonts (default:true)fontsBooleanShorthand for settinginlineFonts+preloadFonts* Values:trueto inline critical font-face rules and preload the fontsfalseto don't inline any font-face rules and don't preload fonts
keyframesStringControls which keyframes rules are inlined.* Values:"critical": (default) inline keyframes rules used by the critical CSS"all"inline all keyframes rules"none"remove all keyframes rules
compressBooleanCompress resulting critical CSS (default:true)logLevelStringControlslog levelof the plugin (default:"info")loggerobjectProvide a custom logger interfaceloggerincludeSelectorsRegExp|StringProvide a list of selectors that should be included in the critical CSS. Accepts both RegExp and string.
We can include or exclude rules to be part of critical CSS by adding comments in the CSS
Single line comments to include/exclude the next CSS rule
/* critters:exclude */
.selector1 {
/* this rule will be excluded from critical CSS */
}
.selector2 {
/* this will be evaluated normally */
}
/* critters:include */
.selector3 {
/* this rule will be included in the critical CSS */
}
.selector4 {
/* this will be evaluated normally */
}Including/Excluding multiple rules by adding start and end markers
/* critters:exclude start */
.selector1 {
/* this rule will be excluded from critical CSS */
}
.selector2 {
/* this rule will be excluded from critical CSS */
}
/* critters:exclude end *//* critters:include start */
.selector3 {
/* this rule will be included in the critical CSS */
}
.selector4 {
/* this rule will be included in the critical CSS */
}
/* critters:include end */By default Critters evaluates the CSS against the entire input HTML. Critters evaluates the Critical CSS by reconstructing the entire DOM and evaluating the CSS selectors to find matching nodes. Usually this works well as Critters is lightweight and fast.
For some cases, the input HTML can be very large or deeply nested which makes the reconstructed DOM much larger, which in turn can slow down the critical CSS generation. Critters is not aware of viewport size and what specific nodes are above the fold since there is not a headless browser involved.
To overcome this issue Critters makes use of Critters containers.
A Critters container mimics the viewport and can be enabled by adding
data-critters-container into the top level container thats contains the HTML
elements above the fold.
You can estimate the contents of your viewport roughly and add a <div
data-critters-container > around the contents.
<html>
<body>
<div class="container">
<div data-critters-container>
/* HTML inside this container are used to evaluate critical CSS
*/
</div>
/* HTML is ignored when evaluating critical CSS */
</div>
<footer></footer>
</body>
</html>Note: This is an easy way to improve the performance of Critters
Custom logger interface:
Type:
object
tracefunction (String) Prints a trace messagedebugfunction (String) Prints a debug messageinfofunction (String) Prints an information messagewarnfunction (String) Prints a warning messageerrorfunction (String) Prints an error message
Controls log level of the plugin. Specifies the level the logger should use. A logger will not produce output for any log level beneath the specified level. Available levels and order are:
- "Info" (default)
- "Warn"
- "Error"
- "Trace"
- "Debug"
- "Silent"
Type: ("Info" | "Warn" | "Error" | "Trace" | "Debug" | "Silent")
The mechanism to use for lazy-loading stylesheets.
Note: JS indicates a strategy requiring JavaScript (falls back to
<noscript> unless disabled).
- default: Move stylesheet links to the end of the document and insert preload meta tags in their place.
- "body": Move all external stylesheet links to the end of the document.
- "media": Load stylesheets asynchronously by adding
media="not x"and removing once loaded. JS - "swap": Convert stylesheet links to preloads that swap to
rel="stylesheet"once loaded (details). JS - "swap-high": Use
<link rel="alternate stylesheet preload">and swap torel="stylesheet"once loaded (details). JS - "js": Inject an asynchronous CSS loader similar to
LoadCSSand use it to load stylesheets. JS - "js-lazy": Like
"js", but the stylesheet is disabled until fully loaded. - false: Disables adding preload tags.
Type: (default | "body" | "media" | "swap" | "swap-high" | "js" |
"js-lazy")
There are a number of other libraries that can inline Critical CSS, each with a slightly different approach. Here are a few great options:
See CHANGELOG.md for a history of changes to this integration.
