Crate critters_rs

Crate critters_rs 

Source
Expand description

§critters-rs

A fast and efficient critical CSS extraction library for Rust, inspired by Google Chrome’s Critters.

Critical CSS extraction involves analyzing HTML documents to identify which CSS rules are actually used on the page, inlining only those critical styles while deferring the loading of non-critical styles. This significantly improves page load performance by reducing render-blocking CSS.

§Features

  • HTML parsing and CSS extraction: Processes HTML documents to identify critical CSS selectors
  • Multiple preload strategies: Configurable strategies for handling non-critical CSS (body-preload, media, swap, etc.)
  • Font preloading: Automatic detection and preloading of critical fonts
  • Keyframe optimization: Intelligent handling of CSS animations and keyframes
  • External stylesheet support: Processes both inline styles and external CSS files
  • High performance: Built with Rust for speed and efficiency

§Basic Usage

use critters_rs::{Critters, CrittersOptions};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a new Critters instance with default options
    let critters = Critters::new(CrittersOptions::default());

    // Process HTML content to extract critical CSS
    let html = r#"
        <html>
            <head>
                <style>
                    .critical { color: red; }
                    .unused { color: blue; }
                </style>
            </head>
            <body>
                <div class="critical">Hello World</div>
            </body>
        </html>
    "#;

    let processed_html = critters.process(html)?;
    // The processed HTML will only contain the .critical style, with .unused removed
    println!("Processed HTML:\n{}", processed_html);

    Ok(())
}

§Advanced Configuration

See CrittersOptions for all available configuration options.

use critters_rs::{Critters, CrittersOptions, PreloadStrategy};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let html_content = r#"
        <html>
            <head>
                <link rel="stylesheet" href="styles.css" />
            </head>
            <body>
                <div class="critical">Hello World</div>
            </body>
        </html>
    "#;

    let options = CrittersOptions {
        path: "./dist".to_string(),
        external: true,
        preload: PreloadStrategy::Swap,
        inline_fonts: true,
        preload_fonts: true,
        compress: true,
        ..Default::default()
    };

    let critters = Critters::new(options);
    let result = critters.process(html_content)?;
    
    println!("Processed HTML:\n{}", result);

    Ok(())
}

Re-exports§

pub use Matcher as SelectorMatcher;

Structs§

Critters
CrittersOptions

Enums§

KeyframesStrategy
Matcher
PreloadStrategy