<p align="center">
  <img src="https://i.imgur.com/J0jv1Sz.png" width="240" height="240" alt="beasties">
  <h1 align="center">Beasties</h1>
</p>

> Beasties is a plugin that inlines your app's [critical CSS] and lazy-loads the rest. It is a maintained fork of [GoogleChromeLabs/critters](https://github.com/GoogleChromeLabs/critters)

## beasties [![npm](https://img.shields.io/npm/v/beasties.svg)](https://www.npmjs.org/package/beasties)

It's a little different from [other options](#similar-libraries), 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](#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 compliment to [prerender-loader](https://github.com/GoogleChromeLabs/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:

```sh
npm i -D beasties
```

or

```sh
yarn add -D beasties
```

## Simple Example

```js
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](https://www.npmjs.org/package/vite-plugin-beasties). [![npm](https://img.shields.io/npm/v/vite-plugin-beasties.svg)](https://www.npmjs.org/package/vite-plugin-beasties)

Just add it to your Vite configuration:

```js
// 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](https://www.npmjs.org/package/beasties-webpack-plugin). [![npm](https://img.shields.io/npm/v/beasties-webpack-plugin.svg)](https://www.npmjs.org/package/beasties-webpack-plugin)

The Webpack plugin supports the same configuration options as the main `beasties` package:

```diff
// 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

<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

### Beasties

All optional. Pass them to `new Beasties({ ... })`.

#### Parameters

- `options`

#### Properties

- `path` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Base path location of the CSS files _(default: `''`)_
- `publicPath` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Public path of the CSS resources. This prefix is removed from the href _(default: `''`)_
- `external` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Inline styles from external stylesheets _(default: `true`)_
- `inlineThreshold` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** Inline external stylesheets smaller than a given size _(default: `0`)_
- `minimumExternalSize` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** If the non-critical external stylesheet would be below this size, just inline it _(default: `0`)_
- `pruneSource` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Remove inlined rules from the external stylesheet _(default: `false`)_
- `mergeStylesheets` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Merged inlined stylesheets into a single `<style>` tag _(default: `true`)_
- `additionalStylesheets` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** Glob for matching other stylesheets to be used while looking for critical CSS.
- `reduceInlineStyles` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/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`)_
- `allowRules` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) | [RegExp](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp)>** Always include rules matching these selectors or patterns in the critical CSS, regardless of whether they match elements in the document. _(default: `[]`)_
- `preload` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Which [preload strategy](#preloadstrategy) to use
- `noscriptFallback` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Add `<noscript>` fallback to JS-based strategies
- `inlineFonts` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Inline critical font-face rules _(default: `false`)_
- `preloadFonts` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Preloads critical fonts _(default: `true`)_
- `fonts` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Shorthand for setting `inlineFonts` + `preloadFonts`\* Values:
  - `true` to inline critical font-face rules and preload the fonts
  - `false` to don't inline any font-face rules and don't preload fonts
- `keyframes` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/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](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Compress resulting critical CSS _(default: `true`)_
- `logLevel` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Controls [log level](#loglevel) of the plugin _(default: `"info"`)_
- `logger` **[object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** Provide a custom logger interface [logger](#logger)

### 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

```css
/* 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

```css
/* beasties:exclude start */

.selector1 {
  /* this rule will be excluded from critical CSS */
}

.selector2 {
  /* this rule will be excluded from critical CSS */
}

/* beasties:exclude end */
```

```css
/* 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 */
```

### 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.

```js
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 thats 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
<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>
```

_Note: This is an easy way to improve the performance of Beasties_

### Logger

Custom logger interface:

Type: [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)

#### Properties

- `trace` **function ([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))** Prints a trace message
- `debug` **function ([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))** Prints a debug message
- `info` **function ([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))** Prints an information message
- `warn` **function ([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))** Prints a warning message
- `error` **function ([String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/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: <kbd>JS</kbd> 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. <kbd>JS</kbd>
- **"swap":** Convert stylesheet links to preloads that swap to `rel="stylesheet"` once loaded ([details](https://www.filamentgroup.com/lab/load-css-simpler/#the-code)). <kbd>JS</kbd>
- **"swap-high":** Use `<link rel="alternate stylesheet preload">` and swap to `rel="stylesheet"` once loaded ([details](http://filamentgroup.github.io/loadCSS/test/new-high.html)). <kbd>JS</kbd>
- **"swap-low":** Use `<link rel="alternate stylesheet">` (no `preload` in `rel` here!) and swap to `rel="stylesheet"` once loaded ([details](http://filamentgroup.github.io/loadCSS/test/new-low.html)). It ensures lowest priority compared to `swap` and `swap-high`. <kbd>JS</kbd>
- **"js":** Inject an asynchronous CSS loader similar to [LoadCSS](https://github.com/filamentgroup/loadCSS) and use it to load stylesheets. <kbd>JS</kbd>
- **"js-lazy":** Like `"js"`, but the stylesheet is disabled until fully loaded.
- **false:** Disables adding preload tags.

Type: (default | `"body"` | `"media"` | `"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:

- [Critical](https://github.com/addyosmani/critical)
- [Penthouse](https://github.com/pocketjoso/penthouse)
- [webpack-critical](https://github.com/lukeed/webpack-critical)
- [webpack-plugin-critical](https://github.com/nrwl/webpack-plugin-critical)
- [html-critical-webpack-plugin](https://github.com/anthonygore/html-critical-webpack-plugin)
- [react-snap](https://github.com/stereobooster/react-snap)

## License

[Apache 2.0](LICENSE)

This is not an official Google product.

[beasties-webpack-plugin]: https://github.com/danielroe/beasties/tree/main/packages/beasties-webpack-plugin
[critical css]: https://www.smashingmagazine.com/2015/08/understanding-critical-css/
[html-webpack-plugin]: https://github.com/jantimon/html-webpack-plugin
