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

_jampackindex.html476index.html984styles.css425styles.css425

SOURCE

  • index.html476
  • styles.css425

JAMPACKED

  • _jampack
  • index.html984
  • styles.css425
SourceOpen in new tab
JampackedOpen in new tab
Terminal
__                                    __    
    |__|____    _____ ___________    ____ |  | __
    |  \__  \  /     \\____ \__  \ _/ ___\|  |/ /
    |  |/ __ \|  Y Y  \  |_> > __ \\  \___|    < 
/\__|  (____  /__|_|  /   __(____  /\___  >__|_ \
\______|    \/      \/|  |       \/     \/     \/
 v0.22.1              |__| by ‹div›RIOTS

Options:
{ onlyoptim: true }

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

 PASS 1 - Optimizing 
▶ index.html
Inlined 365 B (85% of original 425 B) of styles.css.
Time 11.854051
Done: 41.343ms

 Issues 

▶ index.html

 fix  Adding missing  to the top of the 


 1 issue(s) over 1 files