What is critters?
The critters npm package is a tool for Webpack that helps to inline critical CSS and lazy-load the rest. It is designed to improve the performance of web pages by reducing the amount of CSS that needs to be loaded before the page can be rendered. It works by extracting and inlining the critical CSS needed for the initial view and deferring the rest.
What are critters's main functionalities?
Inlining Critical CSS
This feature allows you to inline the critical CSS directly into the HTML to speed up the initial paint of the web page. The code sample shows how to include Critters as a plugin in a Webpack configuration.
const Critters = require('critters-webpack-plugin');
module.exports = {
plugins: [
new Critters({
// Options go here
})
]
};
Lazy-loading Non-critical CSS
Critters can also lazy-load non-critical CSS, which means it will only load the additional CSS when it's needed. The 'preload' option can be set to 'swap' to load fonts using font-display: swap, and 'noscriptFallback' can be enabled to provide a fallback for when JavaScript is not available.
const Critters = require('critters-webpack-plugin');
module.exports = {
plugins: [
new Critters({
preload: 'swap',
noscriptFallback: true
})
]
};
Pruning Unused CSS
Critters can help remove unused CSS rules, reducing the size of the CSS that needs to be loaded. The 'pruneSource' option enables this functionality.
const Critters = require('critters-webpack-plugin');
module.exports = {
plugins: [
new Critters({
pruneSource: true
})
]
};
Other packages similar to critters
purifycss-webpack
PurifyCSS Webpack is a plugin that removes unused selectors from your CSS, similar to the pruning feature of Critters. It differs in that it focuses solely on purifying CSS and does not handle inlining or lazy-loading.
penthouse
Penthouse is a tool that generates critical path CSS for web pages. It is similar to Critters in that it helps identify and inline critical CSS, but it is not a Webpack plugin and requires separate integration into build processes.
loadcss
loadCSS is a function for loading CSS asynchronously, which can be used to lazy-load non-critical CSS. Unlike Critters, it does not provide inlining or pruning features and must be manually integrated into the HTML and JavaScript.
Critters
Critters is a plugin that inlines your app's critical CSS and lazy-loads the rest.
critters
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.
Features
- Fast - no browser, few dependencies
- Integrates with Webpack critters-webpack-plugin
- Supports preloading and/or inlining critical fonts
- Prunes unused CSS keyframes and media queries
- Removes inlined CSS rules from lazy-loaded stylesheets
Installation
First, install Critters as a development dependency:
npm i -D critters
or
yarn add -D critters
Simple Example
import Critters from 'critters';
const critters = new Critters({
});
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);
Usage with webpack
Critters is also available as a Webpack plugin called critters-webpack-plugin.
The Webpack plugin supports the same configuration options as the main critters
package:
// webpack.config.js
+const Critters = require('critters-webpack-plugin');
module.exports = {
plugins: [
+ new Critters({
+ // optional configuration
+ preload: 'swap',
+ includeSelectors: [/^\.btn/, '.banner'],
+ })
]
}
That's it! The resultant html will have its critical CSS inlined and the stylesheets lazy-loaded.
Usage
Critters
All optional. Pass them to new Critters({ ... })
.
Parameters
Properties
path
String Base path location of the CSS files (default: ''
)publicPath
String Public path of the CSS resources. This prefix is removed from the href (default: ''
)external
Boolean Inline styles from external stylesheets (default: true
)inlineThreshold
Number Inline external stylesheets smaller than a given size (default: 0
)minimumExternalSize
Number If the non-critical external stylesheet would be below this size, just inline it (default: 0
)pruneSource
Boolean Remove inlined rules from the external stylesheet (default: false
)mergeStylesheets
Boolean Merged inlined stylesheets into a single <style>
tag (default: true
)additionalStylesheets
Array<String> Glob for matching other stylesheets to be used while looking for critical CSS.reduceInlineStyles
Boolean Option 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 to false
to skip processing inline styles. (default: true
)preload
String Which preload strategy to usenoscriptFallback
Boolean Add <noscript>
fallback to JS-based strategiesinlineFonts
Boolean Inline critical font-face rules (default: false
)preloadFonts
Boolean Preloads critical fonts (default: true
)fonts
Boolean Shorthand for setting inlineFonts
+ preloadFonts
* Values:
true
to inline critical font-face rules and preload the fontsfalse
to don't inline any font-face rules and don't preload fonts
keyframes
String Controls 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
compress
Boolean Compress resulting critical CSS (default: true
)logLevel
String Controls log level of the plugin (default: "info"
)logger
object Provide a custom logger interface loggerincludeSelectors
RegExp | String Provide a list of selectors that should be included in the critical CSS. Accepts both RegExp and string.
Include/exclude rules
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
.selector1 {
}
.selector2 {
}
.selector3 {
}
.selector4 {
}
Including/Excluding multiple rules by adding start and end markers
.selector1 {
}
.selector2 {
}
.selector3 {
}
.selector4 {
}
Critters container
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
Logger
Custom logger interface:
Type: object
Properties
trace
function (String) Prints a trace messagedebug
function (String) Prints a debug messageinfo
function (String) Prints an information messagewarn
function (String) Prints a warning messageerror
function (String) Prints an error message
LogLevel
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"
)
PreloadStrategy
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 to rel="stylesheet"
once loaded (details). JS - "js": Inject an asynchronous CSS loader similar to LoadCSS and 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"
)
Similar Libraries
There are a number of other libraries that can inline Critical CSS, each with a slightly different approach. Here are a few great options:
License
Apache 2.0
This is not an official Google product.