Beasties
Beasties is a plugin that inlines your app's critical CSS and lazy-loads the rest. It is a maintained fork of GoogleChromeLabs/critters
It's a little different from other options, because it doesn't use a headless browser to render content. This tradeoff allows Beasties to be very fast and lightweight. It also means Beasties inlines all CSS rules used by your document, rather than only those needed for above-the-fold content. For alternatives, see Similar Libraries.
Beasties' design makes it a good fit when inlining critical CSS for prerendered/SSR'd Single Page Applications. It was developed to be an excellent complement to prerender-loader, combining to dramatically improve first paint time for most Single Page Applications.
Features
- Fast - no browser, few dependencies
- Integrates with Webpack beasties-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 Beasties as a development dependency:
npm i -D beastiesor
yarn add -D beastiesSimple Example
import Beasties from 'beasties'
const beasties = new Beasties({
// optional configuration (see below)
})
const html = `
<style>
.red { color: red }
.blue { color: blue }
</style>
<div class="blue">I'm Blue</div>
`
const inlined = await beasties.process(html)
console.log(inlined)
// "<style>.blue{color:blue}</style><div class=\"blue\">I'm Blue</div>"Usage with Vite
Beasties can be used with Vite through vite-plugin-beasties.
Just add it to your Vite configuration:
// vite.config.ts
import { defineConfig } from 'vite'
import { beasties } from 'vite-plugin-beasties'
export default defineConfig({
plugins: [
beasties({
// optional beasties configuration
options: {
preload: 'swap',
}
})
]
})The plugin will process the output for your index.html and inline critical CSS while lazy-loading the rest.
Usage with webpack
Beasties is also available as a Webpack plugin called beasties-webpack-plugin.
The Webpack plugin supports the same configuration options as the main beasties package:
// webpack.config.js
+const Beasties = require('beasties-webpack-plugin');
module.exports = {
plugins: [
+ new Beasties({
+ // optional configuration
+ preload: 'swap',
+ })
]
}That's it! The resultant html will have its critical CSS inlined and the stylesheets lazy-loaded.
Usage
Beasties
All optional. Pass them to new Beasties({ ... }).
Parameters
options
Properties
pathString Base path location of the CSS files (default:'')publicPathString Public path of the CSS resources. This prefix is removed from the href (default:'')externalBoolean Inline styles from external stylesheets (default:true)remoteBoolean Download and inline remote stylesheets (http://, https://, //) (default:false)inlineThresholdNumber Inline external stylesheets smaller than a given size (default:0)minimumExternalSizeNumber If the non-critical external stylesheet would be below this size, just inline it (default:0)pruneSourceBoolean Remove inlined rules from the external stylesheet (default:false)mergeStylesheetsBoolean Merged inlined stylesheets into a single<style>tag (default:true)additionalStylesheetsArray<String> Glob for matching other stylesheets to be used while looking for critical CSS.reduceInlineStylesBoolean 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 tofalseto skip processing inline styles. (default:true)allowRulesArray<String | RegExp> Always include rules matching these selectors or patterns in the critical CSS, regardless of whether they match elements in the document. (default:[])preloadString Which preload strategy to usenoscriptFallbackBoolean Add<noscript>fallback to JS-based strategiesnonceString | Function CSP nonce to set on every<style>and<script>element beasties injects, or a function called once per document to derive itinlineFontsBoolean Inline critical font-face rules (default:false)preloadFontsBoolean Preloads critical fonts (default:true)fontsBoolean Shorthand 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
keyframesString 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
compressBoolean Compress resulting critical CSS (default:true)safeParserBoolean Use PostCSS safe parser for fault-tolerant CSS parsing. Handles legacy code with syntax errors (default:true)logLevelString Controls log level of the plugin (default:"info")loggerobject Provide a custom logger interface loggerdedupeWarningsString Suppress repeated identical warnings and errors, either"process"-wide (within a one minute window), per"instance", orfalseto emit every message (default:"process")
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
/* beasties:exclude */
.selector1 {
/* this rule will be excluded from critical CSS */
}
.selector2 {
/* this will be evaluated normally */
}
/* beasties: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
/* beasties:exclude start */
.selector1 {
/* this rule will be excluded from critical CSS */
}
.selector2 {
/* this rule will be excluded from critical CSS */
}
/* beasties:exclude end *//* beasties:include start */
.selector3 {
/* this rule will be included in the critical CSS */
}
.selector4 {
/* this rule will be included in the critical CSS */
}
/* beasties:include end */The supported directives are beasties:include, beasties:exclude, beasties:include start, beasties:include end, beasties:exclude start and beasties:exclude end.
The critters: prefix (from the project beasties was forked from) is still accepted as a deprecated alias and logs a warning. Comments which look like a directive but aren't recognised, such as /* beasties:inclde */ or /* critter:include */, also log a warning rather than being silently ignored.
Programmatically including rules with allowRules
In addition to comment-based inclusion, you can use the allowRules option to programmatically include specific selectors or patterns in the critical CSS, regardless of whether they match elements in the document. This is useful for cases where you know certain styles should always be included.
const beasties = new Beasties({
// Always include these selectors in critical CSS
allowRules: [
// Exact selector match
'.always-include',
// Regular expression pattern
/^\.modal-/
]
})With this configuration, any CSS rules with selectors that match .always-include exactly or start with .modal- will be included in the critical CSS, even if no matching elements exist in the document.
Beasties container
By default Beasties evaluates the CSS against the entire input HTML. Beasties evaluates the Critical CSS by reconstructing the entire DOM and evaluating the CSS selectors to find matching nodes. Usually this works well as Beasties 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. Beasties 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 Beasties makes use of Beasties containers.
A Beasties container mimics the viewport and can be enabled by adding data-beasties-container into the top level container that contains the HTML elements above the fold.
You can estimate the contents of your viewport roughly and add a <div data-beasties-container> around the contents.
<html>
<body>
<div class="container">
<div data-beasties-container>
/* HTML inside this container are used to evaluate critical CSS */
</div>
/* HTML is ignored when evaluating critical CSS */
</div>
<footer></footer>
</body>
</html>You can mark more than one element with data-beasties-container. CSS is then inlined if it matches inside any of the containers, which is useful when the above-the-fold content is spread across multiple disconnected regions.
<html>
<body>
<header data-beasties-container>
/* evaluated */
</header>
<main>
/* ignored */
</main>
<aside data-beasties-container>
/* evaluated */
</aside>
</body>
</html>Note: This is an easy way to improve the performance of Beasties
Skipping individual stylesheets
If a stylesheet should not be processed by Beasties — for example a file that is injected or replaced at runtime (e.g. multi-tenant theming via Docker volume mounts) — add the data-beasties-skip boolean attribute to its <link> tag:
<!-- processed normally -->
<link rel="stylesheet" href="styles.css">
<!-- skipped entirely — tag is left untouched in the final HTML -->
<link rel="stylesheet" href="custom-theme.css" data-beasties-skip>Beasties will not read, inline, prune, or mutate that tag regardless of the active preload strategy. This is useful when disabling inlineCritical globally would sacrifice Core Web Vitals optimizations for the rest of your stylesheets.
Content Security Policy
All preload strategies other than "body", "media-script" and preload: false rely on an inline onload attribute or an inline <script>, both of which are blocked under a strict CSP (script-src-attr 'none', or strict-dynamic alongside a hash or nonce, which makes 'unsafe-inline' inert).
To defer non-critical CSS under a strict CSP, use preload: 'media-script' with a nonce:
const beasties = new Beasties({
preload: 'media-script',
nonce: requestNonce,
})A nonce must be unique per response, so if you reuse one instance across requests, pass a function instead of a string. It is called once per document:
const beasties = new Beasties({
preload: 'media-script',
nonce: document => readNonceFrom(document),
})Deferred links are left as media="print" with the real media value in data-beasties-media, and a single script restores them:
<link rel="stylesheet" href="/style.css" media="print" data-beasties-media="all">
<noscript><link rel="stylesheet" href="/style.css"></noscript>
<!-- ...at the end of <body> -->
<script nonce="...">document.querySelectorAll('link[data-beasties-media]').forEach(function(l){l.media=l.getAttribute('data-beasties-media');l.removeAttribute('data-beasties-media')})</script>Exactly one script is emitted per document and its body never varies, so if you cannot supply a nonce you can allow it with a static script-src hash instead.
Compiler and runtime
Using Beasties per request has two problems: its dependencies are ~1.8 MB of bundle, and every response re-parses the HTML into a DOM and the stylesheets into PostCSS.
But after a build the CSS is usually static, so it can be processed in advance. Two subpath exports split the work: beasties/compiler runs at build time and keeps PostCSS and css-what, beasties/runtime runs per request with no dependencies at all.
classic process() |
beasties/runtime |
|
|---|---|---|
| 13 kB CSS, 21 kB HTML | 3.0ms | 0.4ms |
| 413 kB CSS, 21 kB HTML | 36.1ms | 1.2ms |
| runtime dependencies | 9 (~1.8 MB unpacked) | none (~27 kB) |
1. The compiler turns a stylesheet into a 'plan'
import { compileSheet, encodePlan } from 'beasties/compiler'
const plan = encodePlan(compileSheet(css, { href: '/style.css' }))Rules come out pre-minified, selectors normalised, comment markers and allowRules resolved, url() values rebased, and font and keyframe dependencies extracted. href is what matches a plan to a <link> tag later, so a plan compiled without one never matches and the document passes through untouched.
encodePlan gives you JSON, so plans can be embedded in a server bundle. They are stored compactly, and utility CSS pools well enough to come out smaller than the stylesheet it describes:
| stylesheet | encoded plan |
|---|---|
| 13 kB fixture | 15 kB (1.15x) |
| 413 kB utility-scale | 198 kB (0.48x) |
Decoding costs about 9ms once at startup for a 300 kB plan.
2. The processor makes a single pass over the HTML
import { createProcessor } from 'beasties/runtime'
const processor = createProcessor(plans, { preload: 'media-script' })
const html = processor.process(rendered, { nonce: requestNonce })Tags, classes, ids and attributes are collected, then critical CSS is spliced in as a string rather than round-tripping a DOM. processor.extract(html) returns the critical CSS and font preloads without rewriting the document, if you would rather place them yourself.
Create the processor once and reuse it. Anything that varies per response, like a CSP nonce, belongs in the process() call instead.
Without a DOM, selectors do not apply with 100% accuracy. Simple selectors (a single class, id, tag, or attribute presence) are decided by presence in those token sets; combinators, compound selectors like .a.b, and attribute values compile to a small match program that runs during the same scan, using the open-element stack for ancestor and sibling context. Set exact: false at compile time to fall back to token presence only, which over-inlines combinator selectors but is cheaper and safer.
Options split roughly along the same line:
| option | where |
|---|---|
allowRules, safeParser, exact, comment markers |
build-time |
preload (all strategies), noscriptFallback, keyframes, fonts, inlineFonts, preloadFonts, inlineThreshold, minimumExternalSize, cache, nonce |
runtime |
path, publicPath, external, remote, additionalStylesheets |
configurable |
pruneSource, reduceInlineStyles |
not supported |
Critical CSS is cached per document shape, keyed on a fingerprint of the scanned tokens. Enable cache only for large stylesheets - with smaller ones the scan is the expensive piece.
Note
minimumExternalSize is measured against the rules that weren't inlined, not against the stylesheet. It and inlineThreshold both inline the stylesheet in full and remove its <link> entirely.
Logger
Custom logger interface:
Type: object
Properties
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
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 - "media-script": Like
"media", but instead of an inlineonloadhandler the deferred links are marked withdata-beasties-mediaand a single script at the end of<body>restores their media. The script body is invariant, so it can be allowed with a CSP hash or withoptions.nonce. 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 - "swap-low": Use
<link rel="alternate stylesheet">(nopreloadinrelhere!) and swap torel="stylesheet"once loaded (details). It ensures lowest priority compared toswapandswap-high. 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" | "media-script" | "swap" | "swap-high" | "swap-low" | "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
This is not an official Google product.
