Inline critical CSS

jampack uses critters to inline critical CSS and lazy-loads the rest.

  • Avoids a FOUC while the stylesheet is remotely downloaded after the html content.
  • Improves CLS score of Core Web Vitals.

Configuration

{
  css: {
    inline_critical_css: true,
  }
}

Example

When a stylesheet is loaded on another file like here:

<html>
  <head>
    <title>Testing</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="container">
      <header>
        <div class="banner">Lorem ipsum dolor sit amet</div>
      </header>
    </div>
    <div>
      <h1>Hello World!</h1>
      <p>This is a paragraph</p>
      <input class="input-field" />
      <div class="contents"></div>
      <div class="selected active"></div>
    </div>
    <footer></footer>
  </body>
</html>

Resulting into this HTML where only the relevant critical CSS rules for the first paint are inlined into the <head>:

<html data-critters-container>
  <head>
    <title>Testing</title>
    <style>
h1 {
  color: blue;
}

p {
  color: purple;
}

header {
  padding: 0 50px;
}

.banner {
  font-family: sans-serif;
}

.contents {
  padding: 50px;
  text-align: center;
}

.input-field {
  padding: 10px;
}

footer {
  margin-top: 10px;
}

.container {
  border: 1px solid;
}

div:is(:hover, .active) {
  color: #000;
}

div:is(.selected, :hover) {
  color: #fff;
}
</style>
  <link rel="preload" href="styles.css" as="style">
  </head>
  <body>
    <div class="container">
      <header>
        <div class="banner">Lorem ipsum dolor sit amet</div>
      </header>
    </div>
    <div>
      <h1>Hello World!</h1>
      <p>This is a paragraph</p>
      <input class="input-field">
      <div class="contents"></div>
      <div class="selected active"></div>
    </div>
    <footer></footer>

<link rel="stylesheet" href="styles.css"></body></html>

The rest of the stylesheet is lazy-loaded at the end of the file:

<link rel="stylesheet" href="styles.css">

but preloaded in header for maximum performance:

<link rel="preload" href="styles.css" as="style">

Demo

SOURCE

JAMPACKED

_jampack index.html 505 index.html 949styles.css 425 styles.css 425

SOURCE

  • index.html 505
  • styles.css 425

JAMPACKED

  • _jampack
  • index.html 949
  • styles.css 425
Source Open in new tab
Jampacked Open in new tab
Terminal
__                                    __    
    |__|____    _____ ___________    ____ |  | __
    |  \__  \  /     \\____ \__  \ _/ ___\|  |/ /
    |  |/ __ \|  Y Y  \  |_> > __ \\  \___|    < 
/\__|  (____  /__|_|  /   __(____  /\___  >__|_ \
\______|    \/      \/|  |       \/     \/     \/
 v0.30.0              |__| by ‹div›RIOTS

Options:
{ onlyoptim: true }

Merging default config with:
{
  "css": {
    "inline_critical_css": true
  }
}

 PASS 1 - Optimizing 
▶ index.html
Inlined 365 bytes (85% of original 425 bytes) of styles.css.
Time 10.628666
Done: 29.719ms

 ✔ No issues