critical

repository·master·Indexed 27 days ago

https://github.com/addyosmani/critical

A tool for improving web performance by extracting above-the-fold critical-path CSS, inlining it into HTML, and deferring remaining stylesheets to prevent render-blocking. Version 9.0.0-next.0 features a dual-engine system: a browser-free static engine for SSG/SSR and a Playwright-based render engine for SPAs and viewport-accurate sets. It provides a CLI, a programmatic API, and an MCP server for AI agents.

Tokens
5.1K
Snippets
11
Records
29
Agent score
94%

What's inside critical

  1. Configure inlining and CSP nonces

    master

    When using inline: true, Critical inserts a <style> tag into the <head> and converts <link rel="stylesheet"> tags into <link rel="preload"> tags that are moved to the end of the <body>.

    To support a strict Content Security Policy (CSP), you can pass a nonce within the inline configuration object to stamp the injected <style> tag.

    await critical({
      src: "dist/index.html",
      inline: {
        nonce: "your-csp-nonce"
      }
    });
  2. Run the Critical MCP server for AI agents

    master

    Critical includes a Model Context Protocol (MCP) server that allows AI agents to use it as a tool. The server exposes the optimize_critical_css tool, which accepts src/html (and optional css, engine, inline, width, height) and returns the critical CSS, rewritten HTML, and a structured report.

    Requirements:

    • Requires @modelcontextprotocol/sdk as a peer dependency.

    CLI Usage:

    node src/mcp.js

    Programmatic Usage:

    import { createServer } from "critical/mcp";
  3. Compare Critical with alternative CSS inlining tools

    master

    When choosing a tool for inlining critical-path CSS, consider the trade-offs between viewport awareness, speed, and the type of HTML being processed:

    Critical

    • Best for: Achieving a tight, viewport-accurate critical CSS set, especially for long pages where below-the-fold CSS would otherwise bloat the payload. It is also ideal for Single Page Apps (SPAs) with empty HTML shells because its render engine can measure the app as a browser paints it.
    • Key Feature: Automatically routes between a fast, browser-free static engine and a precise, browser-based render engine (requires Playwright).
    • Output: Provides structured/JSON output, making it suitable for orchestration by build scripts or AI agents.

    Beasties

    • Best for: Statically generated or server-rendered sites where speed and low dependency overhead are priorities. It is the engine behind Next.js's optimizeCss.
    • Key Feature: Extremely fast and lightweight because it does not use a headless browser. It inlines all CSS used by the document.
    • Trade-off: It is not viewport-aware (it inlines all used CSS, including styles for content far below the fold) and requires rendered HTML (it cannot extract CSS from an empty SPA shell).

    Penthouse

    • Best for: Low-level, browser-based extraction when you already have the CSS and a rendered page.
    • Trade-off: It is a lower-level engine; it does not discover stylesheets or handle the inlining/deferring process for you automatically.
  4. Tune the above-the-fold CSS set

    master

    You can optimize the critical CSS set using the following methods:

    • Static Engine Scoping: Mark the container holding your above-the-fold content with the [data-critical-fold] attribute. The static engine will scope matching CSS to that subtree, creating a tighter set without requiring a browser.
    • Viewport Definition (Render Engine): Use width, height, or dimensions to define the "above the fold" area. Providing multiple dimensions will union the results, allowing you to ship a single critical set that covers multiple device types (e.g., mobile and desktop).
    • CSS Preservation: @font-face, @keyframes, and custom properties are preserved if referenced. Unused @keyframes and empty @media, @supports, or @layer blocks are automatically pruned.
  5. Use the critical CLI

    master

    The CLI allows you to process HTML files or entire directories to inline critical CSS and defer the rest of the stylesheets.

    Common tasks:

    • Optimize a directory in place: Use --inline and --write to update all HTML files in a build folder.
    • Dry run/Analysis: Use --explain to see the engine decision and size statistics without modifying files.
    • Single file output: Redirect output to a new file using standard shell redirection.
    • Machine-readable reports: Use --json to emit structured results for CI/CD pipelines.
    # Optimize a build directory in place (inlines critical CSS, defers the rest)
    critical ./dist --inline --write
    
    # See what it would do and why, without writing anything
    critical ./dist --explain
    
    # A single file to stdout
    critical index.html --inline > index.critical.html
  6. Choose a critical CSS tool based on your site architecture

    master

    Use the following decision logic to select the appropriate tool for your project:

    ScenarioRecommended Tool
    Statically generated / SSR site (wanting simplicity and speed)Beasties (or framework-native integrations like Next.js optimizeCss)
    Long pages (where below-the-fold CSS bloats the payload)Critical (using the render engine)
    Single-page app (SPA) (with an empty HTML shell at build time)Critical (using the render engine) or prerender/SSR the page first
    Need structured/JSON output for build scripts or agentsCritical
    Low-level extraction (you already have CSS and a rendered page)Penthouse
  7. Use the Critical MCP server for agentic integration

    master

    The Critical MCP server allows AI agents (like Claude Code) to call Critical's optimization logic directly as a tool. Instead of parsing stdout from a CLI, the agent receives a structured report containing the engine choice, reasoning, and bytes saved, alongside the rewritten HTML.

    To run the server directly via Node.js:

    node src/mcp.js

    Note: This requires @modelcontextprotocol/sdk as a peer dependency. If it is missing, install it using:

    npm i @modelcontextprotocol/sdk
    node src/mcp.js
  8. Use the critical API programmatically

    master

    You can import critical to process HTML and CSS files manually. This is useful when you need to control exactly where the output is written.

    import { writeFile } from "node:fs/promises";
    import { critical } from "critical";
    
    const { html, css } = await critical({ src: "dist/index.html", inline: true });
    await writeFile("dist/index.html", html);
    await writeFile("dist/critical.css", css);
  9. Use the render engine for SPAs

    master

    For Single Page Applications (SPAs) where the initial HTML shell is empty until JavaScript executes, you must use the render engine to ensure the content is captured correctly.

    await critical({ src: "dist/index.html", engine: "render", inline: true });