Monolithic CSS Extraction Plan with Per-Route Critical Splitting and Streaming Hydration Support
This plan outlines a build-time and runtime architecture for extracting CSS in a monolithic bundle (all styles collected centrally), then intelligently splitting it into per-route critical CSS (above-the-fold, render-blocking) and non-critical CSS (lazy-loaded). It supports streaming hydration in SSR frameworks (e.g., React 18+ with Suspense/Qwik/Astro/Next.js app router), ensuring CSS loads progressively without blocking interactivity waterfalls.
Goals & Benefits
Performance : Inline ~10-20KB critical CSS per route (gzip); defer rest.
Monolithic Base : Shared global/base styles in one file; route-specific splits.
Streaming Hydration : CSS emitted at hydration boundaries (e.g., Suspense fallbacks/stream chunks) to match streamed HTML/JS.
Cache Efficiency : Shared monolithic CSS caches globally; splits are small/route-specific.
Zero-Runtime Cost : All extraction at build-time.
Framework Agnostic : Adaptable to Next.js, Remix, Qwik, or custom SSR (uses Vite/Rollup/Webpack).
Metric Monolithic Baseline This Plan LCP (Largest Contentful Paint) 2.5s <1.5s CSS Size (initial) 200KB 15KB inline + 185KB async Hydration Waterfall Full block Progressive (per boundary)
Architecture Overview
code Copy code
Build-Time:
Routes → Render (headless SSR) → Analyze DOM → Extract Critical CSS → Split & Hash
Artifacts:
/css/
monolithic-base.css (global resets, fonts, shared)
critical/[routeHash].css (inline per-route)
non-critical/[routeHash].css (async preload)
manifests/route-css-map.json (route → CSS hashes)
Runtime (SSR Streaming):
HTML Head: <style>monolithic-base + critical</style>
<link rel="preload" as="style" href="/css/non-critical/[hash].css" />
Suspense Boundaries: Emit <style> for child route CSS
Key Components
Monolithic Collector : Aggregates all CSS (globals + components).
Per-Route Analyzer : Simulates viewport, extracts used rules.
Splitter : Dedupes shared rules → base + unique/route.
Hydration Emitter : Hooks into SSR stream for boundary-aware injection.
Manifest : JSON map for route → CSS chunks (used in SSR/CSR).
Implementation Phases
Phase 1: Build Pipeline Setup (Webpack/Vite/Rollup Plugin)
Use a custom plugin chain. Example: Vite plugin (vite-plugin-css-splitter).
javascript Copy code
// vite.config.js
import { defineConfig } from 'vite';
import cssSplitter from './plugins/css-splitter.js'; // Custom plugin (below)
export default defineConfig({
plugins: [react(), cssSplitter({ routes: './src/routes' })]
});
Custom Plugin Structure (plugins/css-splitter.js):
javascript Copy code
import Critters from 'critters'; // Critical CSS extractor
import { JSDOM } from 'jsdom'; // Headless DOM
import fs from 'fs';
import path from 'path';
export default function cssSplitter(opts) {
let allCssRules = new Map(); // Monolithic: selector → rule
let routeCssMap = {}; // route → { critical: rules[], noncrit: rules[] }
return {
name: 'css-splitter',
// 1. Collect all CSS monolithically
transform(code, id) {
if (id.endsWith('.css')) {
const rules = parseCssRules(code); // Custom parser (postcss)
rules.forEach(rule => allCssRules.set(rule.selector, rule));
return code; // Bundle as monolithic temporarily
}
},
// 2. Per-route analysis (generate)
async generateBundle() {
for (const routePath of await getRoutes(opts.routes)) { // e.g., file-system routes
const html = await renderRouteSSR(routePath); // Puppeteer/Playwright headless or JSDOM
const criticalCss = new Critters({
/* viewport: 1300x900, pruneUnused: true */
}).processSync(html);
// Split: critical rules → route, unused → noncrit
routeCssMap[routePath] = splitRules(allCssRules, criticalCss);
}
// Dedupe: shared rules → monolithic-base.css
const baseRules = extractSharedRules(routeCssMap);
fs.writeFileSync('dist/css/monolithic-base.css', serializeCss(baseRules));
// Emit splits & manifest
Object.entries(routeCssMap).forEach(([route, { crit, noncrit }]) => {
const critHash = hash(serializeCss(crit));
fs.writeFileSync(`dist/css/critical/${critHash}.css`, serializeCss(crit));
fs.writeFileSync(`dist/css/non-critical/${hash(serializeCss(noncrit))}.css`, serializeCss(noncrit));
});
fs.writeFileSync('dist/manifests/route-css-map.json', JSON.stringify(routeCssMap));
}
};
}
// Helpers: parseCssRules, renderRouteSSR (use framework's SSR fn), splitRules (AST diff), etc.
Tools :
Tool Purpose Critters Critical extraction PostCSS Rule parsing/deduping Playwright Accurate SSR rendering (better than JSDOM for complex apps) lightningcss Minification + hashing
Phase 2: SSR Runtime Integration (Streaming Hydration)
Hook into SSR renderer to inject CSS progressively.
Example: React/Next.js Custom Document/App :
jsx Copy code
// app/layout.tsx or _document.js
import { readFileSync } from 'fs';
import routeCssMap from '../manifests/route-css-map.json';
function getCssForRoute(route, type) {
const { critHash } = routeCssMap[route] || {};
return readFileSync(`css/${type}/${critHash}.css`, 'utf8');
}
export default function RootLayout({ children, route }) {
return (
<html>
<head>
{/* Monolithic base + route critical (blocking) */}
<style id="base-css">{readFileSync('css/monolithic-base.css', 'utf8')}</style>
<style id="critical-css" dangerouslySetInnerHTML={{ __html: getCssForRoute(route, 'critical') }} />
{/* Non-critical preload */}
<link rel="preload" href={`/css/non-critical/${noncritHash}.css`} as="style" />
<link rel="stylesheet" href={`/css/non-critical/${noncritHash}.css`} media="print" onload="this.media='all'" />
</head>
<body>
{/* Streaming children with boundary CSS */}
<Suspense fallback={<CriticalCssEmitter route={childRoute} />}>
{children}
</Suspense>
</body>
</html>
);
}
// Boundary Emitter Component (streams <style> at Suspense edges)
function CriticalCssEmitter({ route }) {
useEffect(() => {
const style = document.createElement('style');
style.textContent = getCssForRoute(route, 'critical');
document.head.appendChild(style);
}, []);
return <div>Loading...</div>; // Fallback
}
Streaming Flow :
Server streams HTML head → base + parent critical CSS.
Hits Suspense → streams fallback + child critical CSS inline.
Hydrates progressively (React Compiler/SuspenseList optimizes).
Client: Non-critical loads async, media-query tricked for FOUC-free.
Qwik/Astro Adaptation : Use useStylesScoped() or renderStyles() hooks.
Phase 3: Optimizations & Edge Cases
Shared Rules Deduping : Use PostCSS cssnano + rule frequency scoring (>50% routes → base).
Dynamic Routes : [slug] → Build-time params scan + runtime fallback to generic critical.
Fonts/Icons : Pre-extract to base; use font-display: swap.
Preflight : Tailwind/PostCSS nesting → handled in monolithic collect.
Dev Mode : Disable splits; use ?css=monolithic.
Metrics : Integrate Web Vitals logging; rebuild if >10% routes exceed 20KB critical.
Caching : ETags/hashes; SW precache splits.
Edge Case Solution JS-Driven CSS (CSS-in-JS) Extract via emotion/server or styled-components. Theming Parametrize splits (e.g., critical-dark-[route].css). SPAs Use history.listen to swap CSS on route change. Mobile Viewports Multi-viewport analysis (375x667, 1300x900).
Phase 4: Validation & Rollout
Build Test : npm run build → Verify manifests, CSS sizes.
Lighthouse Audit : Target 100/100 perf.
A/B Test : Compare vs. monolithic.
Monitoring : Sentry + CSS load errors.
This plan is production-ready, scales to 1000+ routes (parallel builds), and integrates in <1 week for most stacks. Source: Inspired by Next.js 14 RSC CSS, Partytown, and Critters. Ping for code repo!