Claude Skills Guide

Critical CSS is one of the most impactful optimizations you can make for your website’s performance. By inlining the CSS needed to render above-the-fold content and deferring the rest, you can dramatically reduce render-blocking resources and improve First Contentful Paint (FCP). In this tutorial, we’ll explore how to use Claude Code to automate and streamline your critical CSS workflow.

What is Critical CSS?

Critical CSS is the subset of CSS rules that the browser needs to render the initial viewport of your page. Instead of loading your entire stylesheet (which can be hundreds of kilobytes), the browser only downloads and processes the essential styles needed for above-the-fold content. This approach significantly improves perceived load time and Core Web Vitals.

Why Critical CSS Matters

Setting Up Your Critical CSS Workflow

Before we dive into Claude Code integration, let’s set up a basic project structure. We’ll assume you have a modern web project with a CSS build process.

Project Structure

// critical-css-project/
// ├── src/
// │   ├── styles/
// │   │   ├── main.css
// │   │   └── components.css
// ├── dist/
// └── critical.config.js

Installing Required Tools

You’ll need a few tools to generate critical CSS effectively:

npm install --save-dev critical penthouse inline-critical

Automating Critical CSS with Claude Code

Claude Code excels at automating repetitive tasks. Let’s create a comprehensive workflow that generates, inlines, and optimizes critical CSS automatically.

Creating Your First Claude Code Script

Create a file named critical-workflow.js in your project:

const critical = require('critical');
const fs = require('fs');
const path = require('path');

async function generateCriticalCSS() {
  const options = {
    // Base directory for your project
    base: './dist',
    // HTML source file
    src: 'index.html',
    // Output file for critical CSS
    target: {
      html: 'index-critical.html',
      css: 'critical.min.css',
      inline: true
    },
    // Viewport dimensions
    dimensions: [
      {
        width: 375,
        height: 667 // Mobile
      },
      {
        width: 1280,
        height: 720 // Desktop
      }
    ],
    // Minify the output
    minify: true,
    // Include background images
    include: [
      'body',
      '.hero',
      '.content'
    ]
  };

  try {
    await critical.generate(options);
    console.log('✅ Critical CSS generated successfully!');
  } catch (error) {
    console.error('❌ Error generating critical CSS:', error);
    throw error;
  }
}

generateCriticalCSS();

Running the Workflow

Execute the script with Node.js:

node critical-workflow.js

Integrating with Your Build Process

For a fully automated workflow, integrate the critical CSS generation into your build pipeline. Here’s how to add it to your package.json:

{
  "scripts": {
    "build:css": "sass src/styles:dist/styles",
    "build:html": "eleventy",
    "critical": "node critical-workflow.js",
    "build": "npm run build:css && npm run build:html && npm run critical"
  }
}

Advanced: Multi-Page Critical CSS

For larger sites, you’ll want to generate critical CSS for multiple pages:

const critical = require('critical');
const glob = require('glob');

const pages = [
  { src: 'index.html', target: 'index-critical.html' },
  { src: 'about.html', target: 'about-critical.html' },
  { src: 'contact.html', target: 'contact-critical.html' }
];

async function generateAllCriticalCSS() {
  for (const page of pages) {
    await critical.generate({
      src: page.src,
      target: {
        html: page.target,
        css: `critical-${path.basename(page.src, '.html')}.css`,
        inline: true
      },
      dimensions: [
        { width: 375, height: 667 },
        { width: 1280, height: 720 }
      ],
      minify: true
    });
    console.log(`✅ Processed: ${page.src}`);
  }
}

generateAllCriticalCSS();

Optimizing Your Workflow with Claude Code Prompts

Claude Code can help you generate optimized prompts for your critical CSS workflow. Here’s a sample prompt you can use:

Create a Node.js script that:
1. Reads all HTML files from the dist/ directory
2. Generates critical CSS for each page
3. Inlines the critical CSS into the HTML
4. Saves the optimized files to a separate directory
5. Includes error handling and logging

Handling Dynamic Content

Critical CSS becomes challenging with dynamic content. Here are strategies to handle this:

// Configuration for different content types
const contentConfigs = {
  // Static pages - straightforward critical CSS
  static: {
    dimensions: [{ width: 375, height: 667 }],
    include: ['body', 'header', 'main', 'footer']
  },
  // Dynamic/AMP pages - minimal critical CSS
  amp: {
    dimensions: [{ width: 375, height: 667 }],
    include: ['body', '.amp-header'],
    inline: true
  },
  // Landing pages - comprehensive critical CSS
  landing: {
    dimensions: [
      { width: 375, height: 667 },
      { width: 768, height: 1024 },
      { width: 1280, height: 720 }
    ],
    include: ['body', '.hero', '.features', '.cta']
  }
};

Best Practices for Critical CSS

Follow these best practices to maximize the effectiveness of your critical CSS implementation:

1. Keep Critical CSS Small

Aim for under 10KB of critical CSS. Larger files defeat the purpose of the optimization. Use CSS purging and minification to keep sizes down.

2. Inline Strategically

Only inline critical CSS in the <head>. Non-critical CSS should be loaded asynchronously or deferred:

<!-- Inlined critical CSS -->
<style>
  /* Critical CSS here */
</style>

<!-- Non-critical CSS loaded async -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>

3. Test Across Devices

Always test critical CSS across multiple viewport sizes. What works on desktop may not work on mobile and vice versa.

4. Automate the Workflow

Integrate critical CSS generation into your CI/CD pipeline to ensure every deployment includes optimized CSS:

# Example CI/CD command
npm run build && npx critical css/dist/index.html --inline --minify

Troubleshooting Common Issues

CSS Not Inlining

If your CSS isn’t inlining, check:

Incorrect Critical Path

If above-the-fold content looks wrong:

Conclusion

Automating your critical CSS workflow with Claude Code can significantly improve your site’s performance while reducing manual effort. By following this tutorial, you’ve learned how to:

Remember, critical CSS is just one piece of the performance puzzle. Combine it with other optimizations like image compression, code splitting, and lazy loading for the best results.

Start implementing critical CSS in your projects today and watch your Core Web Vitals improve!

Built by theluckystrike — More at zovo.one