# Critical CSS Extraction Plan with Per-Route Splitting & Streaming Hydration
1. High-Level Strategy
We'll extract critical CSS per route, split it into modular chunks, and integrate with streaming hydration for optimal performance.
2. Architecture Overview
graph TD
A[Monolithic CSS Bundle] --> B[CSS Analyzer]
B --> C[Route Mapper]
C --> D[Critical CSS Extractor]
D --> E[Per-Route CSS Chunks]
F[App Routes] --> G[Route Definitions]
G --> C
E --> H[Streaming Server]
H --> I[HTML Stream]
I --> J[Client Hydration]
J --> K[Progressive CSS Loading]
K --> L[Hydrated Components]
3. Implementation Plan
Phase 1: CSS Analysis & Route Mapping
// css-analyzer.ts
import { Project, SourceFile } from 'ts-morph';
import { parse } from '@babel/parser';
import traverse from '@babel/traverse';
import fs from 'fs';
import path from 'path';
interface RouteConfig {
path: string;
component: string;
imports: string[];
styles: string[];
}
interface CSSAnalysisResult {
routeMap: Map<string, string[]>;
globalStyles: string[];
unusedStyles: string[];
}
class CSSAnalyzer {
private project: Project;
private routeConfigs: RouteConfig[] = [];
constructor(private config: {
tsConfigPath: string;
routesPath: string;
cssGlob: string;
}) {
this.project = new Project({
tsConfigFilePath: config.tsConfigPath,
});
}
async analyze(): Promise<CSSAnalysisResult> {
// 1. Extract route definitions
await this.extractRoutes();
// 2. Map components to styles
const routeMap = await this.mapStylesToRoutes();
// 3. Identify global styles
const globalStyles = await this.identifyGlobalStyles();
// 4. Detect unused styles
const unusedStyles = await this.findUnusedStyles();
return {
routeMap,
globalStyles,
unusedStyles
};
}
private async extractRoutes(): Promise<void> {
const routesFile = this.project.getSourceFile(this.config.routesPath);
if (!routesFile) throw new Error('Routes file not found');
const routeDeclarations = this.parseRouteConfig(routesFile);
this.routeConfigs = routeDeclarations;
}
private parseRouteConfig(sourceFile: SourceFile): RouteConfig[] {
const routes: RouteConfig[] = [];
// Parse route definitions (simplified)
const functionDeclarations = sourceFile.getFunctions();
functionDeclarations.forEach(fn => {
const body = fn.getBody();
if (body) {
// Extract route info from function body
// This is simplified - real implementation would use AST
const routeMatch = body.getText().match(/path:\s*['"]([^'"]+)['"]/);
const componentMatch = body.getText().match(/component:\s*(\w+)/);
if (routeMatch && componentMatch) {
routes.push({
path: routeMatch[1],
component: componentMatch[1],
imports: [],
styles: []
});
}
}
});
return routes;
}
private async mapStylesToRoutes(): Promise<Map<string, string[]>> {
const routeStyleMap = new Map<string, string[]>();
for (const route of this.routeConfigs) {
const componentStyles = await this.findComponentStyles(route.component);
routeStyleMap.set(route.path, componentStyles);
}
return routeStyleMap;
}
private async findComponentStyles(componentName: string): Promise<string[]> {
// Find all CSS files imported by this component and its dependencies
const componentFile = this.project.getSourceFile(s =>
s.getBaseName().includes(componentName)
);
if (!componentFile) return [];
const imports = componentFile.getImportDeclarations();
const styles: string[] = [];
for (const imp of imports) {
const source = imp.getModuleSpecifier().getText();
if (source.endsWith('.css') || source.endsWith('.scss')) {
styles.push(source);
}
}
return styles;
}
private async identifyGlobalStyles(): Promise<string[]> {
// Find styles used across multiple routes
return [];
}
private async findUnusedStyles(): Promise<string[]> {
// Detect CSS not referenced by any component
return [];
}
}
Phase 2: Critical CSS Extraction Pipeline
// critical-css-extractor.ts
import { extractCritical } from 'critical';
import { PurgeCSS } from 'purgecss';
import postcss from 'postcss';
import cssnano from 'cssnano';
import { CSSAnalyzer, CSSAnalysisResult } from './css-analyzer';
interface ExtractionOptions {
routes: string[];
outputPath: string;
inlineCritical?: boolean;
minify?: boolean;
}
interface CriticalCSSResult {
route: string;
criticalCSS: string;
deferredCSS: string;
unusedCSS: string;
stats: {
originalSize: number;
criticalSize: number;
deferredSize: number;
};
}
class CriticalCSSExtractor {
private analyzer: CSSAnalyzer;
constructor(private options: ExtractionOptions) {
this.analyzer = new CSSAnalyzer({
tsConfigPath: './tsconfig.json',
routesPath: './src/routes.tsx',
cssGlob: './src/**/*.css'
});
}
async extract(): Promise<Map<string, CriticalCSSResult>> {
const analysis = await this.analyzer.analyze();
const results = new Map<string, CriticalCSSResult>();
for (const route of this.options.routes) {
const result = await this.extractRouteCriticalCSS(route, analysis);
results.set(route, result);
}
return results;
}
private async extractRouteCriticalCSS(
route: string,
analysis: CSSAnalysisResult
): Promise<CriticalCSSResult> {
const routeStyles = analysis.routeMap.get(route) || [];
// Combine all CSS for this route
const fullCSS = await this.combineCSS(routeStyles);
const originalSize = fullCSS.length;
// Extract critical CSS for route
const criticalResult = await this.extractCriticalForRoute(route, fullCSS);
// Generate deferred CSS
const deferredCSS = await this.generateDeferredCSS(fullCSS, criticalResult);
// Minify if needed
const criticalCSS = this.options.minify
? await this.minifyCSS(criticalResult.css)
: criticalResult.css;
return {
route,
criticalCSS,
deferredCSS,
unusedCSS: '', // Would be populated from analysis
stats: {
originalSize,
criticalSize: criticalCSS.length,
deferredSize: deferredCSS.length
}
};
}
private async extractCriticalForRoute(route: string, css: string) {
// Use a headless browser to render route and extract critical CSS
return await extractCritical({
base: './',
html: await this.renderRouteHTML(route),
css: css,
dimensions: [
{ width: 320, height: 568 },
{ width: 768, height: 1024 },
{ width: 1280, height: 800 },
{ width: 1920, height: 1080 }
],
extract: true
});
}
private async renderRouteHTML(route: string): Promise<string> {
// Use JSDOM or Puppeteer to render route HTML
// This would integrate with your framework's SSR
return '';
}
private async generateDeferredCSS(fullCSS: string, criticalResult: any): Promise<string> {
// Remove critical CSS from full bundle
const deferredCSS = fullCSS.replace(criticalResult.css, '');
// Optimize deferred CSS
return await postcss([
cssnano({ preset: 'default' })
]).process(deferredCSS, { from: undefined }).then(r => r.css);
}
private async combineCSS(stylePaths: string[]): Promise<string> {
// Combine multiple CSS files
return stylePaths.map(path => fs.readFileSync(path, 'utf-8')).join('\n');
}
private async minifyCSS(css: string): Promise<string> {
return await postcss([
cssnano({ preset: 'advanced' })
]).process(css, { from: undefined }).then(r => r.css);
}
}
Phase 3: Streaming Hydration Integration
// streaming-hydration.ts
import { Writable } from 'stream';
import { RenderToPipeableStreamOptions } from 'react-dom/server';
interface HydrationStreamOptions extends RenderToPipeableStreamOptions {
route: string;
criticalCSS: string;
deferredCSSUrl?: string;
}
class StreamingHydrationManager {
private criticalCSSMap: Map<string, string>;
constructor() {
this.criticalCSSMap = new Map();
}
registerCriticalCSS(route: string, css: string) {
this.criticalCSSMap.set(route, css);
}
createHydrationStream(options: HydrationStreamOptions) {
const { route, criticalCSS, deferredCSSUrl, ...streamOptions } = options;
return {
// This would integrate with React 18's renderToPipeableStream
bootstrapScripts: [
'/src/entry-client.tsx'
],
bootstrapModules: [
'/src/hydration-runtime.ts'
],
onShellReady() {
// The content above all Suspense boundaries is ready
console.log('Shell ready for route:', route);
},
onShellError(error) {
console.error('Shell error:', error);
},
onAllReady() {
console.log('All content ready for route:', route);
},
onError(error) {
console.error('Streaming error:', error);
},
...streamOptions
};
}
// Client-side hydration runtime
getHydrationRuntime() {
return `
// Progressive CSS loading
const loadDeferredCSS = (url) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
document.head.appendChild(link);
};
// Intersection Observer for component-level hydration
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const component = entry.target;
const cssUrl = component.dataset.deferredCss;
if (cssUrl) {
loadDeferredCSS(cssUrl);
observer.unobserve(component);
}
}
});
});
// Initialize hydration
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('[data-deferred-css]').forEach(el => {
observer.observe(el);
});
});
`;
}
}
Phase 4: Build System Integration
// build-plugin.ts
import { Plugin } from 'vite';
import { CriticalCSSExtractor } from './critical-css-extractor';
import { StreamingHydrationManager } from './streaming-hydration';
interface PluginOptions {
routes: string[];
outputPath: string;
minify?: boolean;
}
export function criticalCSSPlugin(options: PluginOptions): Plugin {
const extractor = new CriticalCSSExtractor(options);
const hydrationManager = new StreamingHydrationManager();
return {
name: 'critical-css-extraction',
enforce: 'post',
async buildStart() {
console.log('Starting critical CSS extraction...');
const results = await extractor.extract();
// Register critical CSS for each route
results.forEach((result, route) => {
hydrationManager.registerCriticalCSS(route, result.criticalCSS);
});
},
async generateBundle(options, bundle) {
// Add critical CSS to build output
const criticalChunks: Record<string, string> = {};
hydrationManager['criticalCSSMap'].forEach((css, route) => {
const safeRouteName = route.replace(/[^a-zA-Z0-9]/g, '-');
criticalChunks[`critical-${safeRouteName}`] = css;
});
// Add to bundle
Object.entries(criticalChunks).forEach(([name, css]) => {
bundle[`${name}.css`] = {
type: 'asset',
fileName: `assets/${name}.css`,
source: css,
originalFileName: `${name}.css`
} as any;
});
},
transformIndexHtml: {
enforce: 'post',
transform(html, ctx) {
// Inject critical CSS into HTML
const route = ctx.path || '/';
const criticalCSS = hydrationManager['criticalCSSMap'].get(route);
if (criticalCSS) {
return html.replace(
'</head>',
`<style>${criticalCSS}</style></head>`
);
}
return html;
}
}
};
}
Phase 5: Server-Side Rendering Integration
// server-renderer.ts
import { renderToPipeableStream } from 'react-dom/server';
import { StreamingHydrationManager } from './streaming-hydration';
import fs from 'fs';
import path from 'path';
class ServerRenderer {
private hydrationManager: StreamingHydrationManager;
constructor() {
this.hydrationManager = new StreamingHydrationManager();
this.loadCriticalCSS();
}
private loadCriticalCSS() {
// Load pre-extracted critical CSS from build output
const criticalDir = path.join(process.cwd(), 'dist/critical-css');
if (fs.existsSync(criticalDir)) {
fs.readdirSync(criticalDir).forEach(file => {
if (file.endsWith('.css')) {
const route = file.replace('critical-', '').replace('.css', '');
const css = fs.readFileSync(path.join(criticalDir, file), 'utf-8');
this.hydrationManager.registerCriticalCSS(route, css);
}
});
}
}
async renderRoute(route: string, res: any, App: any) {
const criticalCSS = this.hydrationManager['criticalCSSMap'].get(route) || '';
const streamOptions = this.hydrationManager.createHydrationStream({
route,
criticalCSS,
deferredCSSUrl: `/assets/deferred-${route.replace(/[^a-zA-Z0-9]/g, '-')}.css`,
bootstrapScripts: ['/src/entry-client.tsx']
});
const { pipe } = renderToPipeableStream(
<App />,
streamOptions
);
// Set headers for streaming
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Transfer-Encoding', 'chunked');
// Inject critical CSS in head
res.write(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>${criticalCSS}</style>
<script>
${this.hydrationManager.getHydrationRuntime()}
</script>
</head>
<body>
<div id="root">
`);
// Pipe the React stream
pipe(res);
// Close HTML after stream ends
res.write(`
</div>
</body>
</html>
`);
}
}
Phase 6: Development Workflow
# Development script
npm run dev
# 1. Start with initial CSS analysis
npm run analyze-css
# 2. Extract critical CSS for all routes
npm run extract-critical
# 3. Start development server with live CSS updates
npm run dev --watch-css
Phase 7: Monitoring & Optimization
// css-monitor.ts
import { PerformanceObserver } from 'perf_hooks';
class CSSMonitor {
private metrics: Map<string, any> = new Map();
constructor() {
this.setupPerformanceObserver();
}
private setupPerformanceObserver() {
const obs = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.name.includes('css')) {
this.recordMetric(entry);
}
});
});
obs.observe({ entryTypes: ['measure', 'resource'] });
}
private recordMetric(entry: any) {
this.metrics.set(entry.name, {
duration: entry.duration,
startTime: entry.startTime,
size: (entry as any).encodedBodySize || 0
});
}
generateReport(): Record<string, any> {
return Object.fromEntries(this.metrics);
}
}
4. Summary
This plan provides a comprehensive approach to:
- Extract Critical CSS Per Route: Analyze each route and extract only the CSS needed for above-the-fold content
- Streaming Hydration Support: Integrate with React 18's streaming SSR for progressive loading
- Modular Architecture: Separate concerns into analyzer, extractor, hydration manager, and build plugin
- Development Workflow: Automated pipeline for CSS extraction and updates
- Performance Monitoring: Track CSS loading performance and optimization opportunities
Key Benefits
- Reduced Initial Load: Only load critical CSS initially
- Progressive Enhancement: Load additional styles as needed
- Better TTI: Improved Time to Interactive with streaming hydration
- Maintainability: Clear separation of concerns and modular architecture
- Scalability: Handles applications with many routes efficiently
Monolithic CSS Extraction Plan: Per-Route Critical CSS with Streaming Hydration
Architecture Overview
graph TB
subgraph "Build Time"
A[Monolithic CSS Bundle] --> B[CSS Analyzer]
B --> C[AST-based Component Mapping]
C --> D[Critical CSS Extractor]
D --> E[Per-Route CSS Chunks]
E --> F[Inline Critical CSS]
E --> G[Deferred CSS Files]
end
subgraph "Server Runtime"
H[Request Handler] --> I[Route Detection]
I --> J[Streaming Renderer]
J --> K[Critical CSS Injection]
K --> L[Shell Stream]
L --> M[Progressive Chunks]
end
subgraph "Client Runtime"
N[HTML Shell] --> O[Critical Styles Applied]
O --> P[Streaming Hydration]
P --> Q[Lazy CSS Loading]
Q --> R[Full Hydration]
end
F --> K
G --> Q
Phase 1: CSS Analysis Infrastructure
1.1 CSS Dependency Graph Builder
// css-analyzer/dependency-graph.ts
import { Project, SourceFile, ImportDeclaration } from 'ts-morph';
import { createHash } from 'crypto';
import * as postcss from 'postcss';
import * as selectorParser from 'postcss-selector-parser';
interface StyleDependency {
importPath: string;
selectors: string[];
classes: string[];
ids: string[];
variables: string[];
mixins: string[];
fileHash: string;
}
interface ComponentStyleMapping {
componentPath: string;
componentName: string;
directStyles: StyleDependency[];
transitiveStyles: StyleDependency[];
usedSelectors: Set<string>;
}
export class CSSDependencyGraph {
private project: Project;
private componentMap: Map<string, ComponentStyleMapping> = new Map();
private styleCache: Map<string, StyleDependency> = new Map();
constructor(tsConfigPath: string) {
this.project = new Project({ tsConfigFilePath: tsConfigPath });
}
async buildGraph(sourcePatterns: string[]): Promise<void> {
const sourceFiles = this.project.getSourceFiles(sourcePatterns);
for (const file of sourceFiles) {
await this.analyzeComponentFile(file);
}
await this.resolveTransitiveDependencies();
}
private async analyzeComponentFile(file: SourceFile): Promise<void> {
const componentName = this.extractComponentName(file);
const imports = file.getImportDeclarations();
const styleImports: StyleDependency[] = [];
for (const imp of imports) {
const moduleSpecifier = imp.getModuleSpecifierValue();
if (this.isStyleImport(moduleSpecifier)) {
const styleDep = await this.analyzeStyleFile(moduleSpecifier, file.getFilePath());
styleImports.push(styleDep);
}
}
const usedSelectors = await this.extractUsedSelectors(file);
this.componentMap.set(file.getFilePath(), {
componentPath: file.getFilePath(),
componentName,
directStyles: styleImports,
transitiveStyles: [],
usedSelectors
});
}
private async analyzeStyleFile(importPath: string, importerPath: string): Promise<StyleDependency> {
const resolvedPath = this.resolveStylePath(importPath, importerPath);
if (this.styleCache.has(resolvedPath)) {
return this.styleCache.get(resolvedPath)!;
}
const content = await fs.readFile(resolvedPath, 'utf-8');
const fileHash = createHash('md5').update(content).digest('hex');
const ast = postcss.parse(content);
const selectors: string[] = [];
const classes: string[] = [];
const ids: string[] = [];
const variables: string[] = [];
// Extract CSS custom properties
ast.walkDecls(decl => {
if (decl.prop.startsWith('--')) {
variables.push(decl.prop);
}
});
// Extract selectors
ast.walkRules(rule => {
selectorParser(selectors => {
selectors.walk(selector => {
const selectorStr = selector.toString();
selectors.push(selectorStr);
if (selector.type === 'class') {
classes.push((selector as any).value);
} else if (selector.type === 'id') {
ids.push((selector as any).value);
}
});
}).processSync(rule.selector);
});
const dependency: StyleDependency = {
importPath: resolvedPath,
selectors: [...new Set(selectors)],
classes: [...new Set(classes)],
ids: [...new Set(ids)],
variables: [...new Set(variables)],
mixins: [], // Would be populated for SCSS
fileHash
};
this.styleCache.set(resolvedPath, dependency);
return dependency;
}
private async extractUsedSelectors(file: SourceFile): Promise<Set<string>> {
const usedSelectors = new Set<string>();
const classes = file.getClasses();
for (const cls of classes) {
// Extract class names from className attributes
const jsxElements = cls.getDescendantsOfKind(SyntaxKind.JsxElement);
for (const element of jsxElements) {
const openingElement = element.getOpeningElement();
const attributes = openingElement.getAttributes();
for (const attr of attributes) {
if (Node.isJsxAttribute(attr) && attr.getName() === 'className') {
const value = attr.getInitializer();
if (value) {
const classNameValue = value.getText().replace(/['"]/g, '');
classNameValue.split(/\s+/).forEach(cn => usedSelectors.add(`.${cn}`));
}
}
}
}
}
return usedSelectors;
}
getComponentStyles(componentPath: string): ComponentStyleMapping | undefined {
return this.componentMap.get(componentPath);
}
}
1.2 Route-Based Style Aggregator
// css-analyzer/route-aggregator.ts
import { RouteConfig } from './types';
interface RouteStyleManifest {
route: string;
componentTree: string[];
aggregatedStyles: AggregatedStyle[];
criticalSelectors: string[];
deferredSelectors: string[];
estimatedCriticalSize: number;
}
interface AggregatedStyle {
source: string;
selectors: string[];
priority: 'critical' | 'high' | 'low';
loadingStrategy: 'inline' | 'preload' | 'lazy';
}
export class RouteStyleAggregator {
private dependencyGraph: CSSDependencyGraph;
private routeConfigs: RouteConfig[];
constructor(dependencyGraph: CSSDependencyGraph, routeConfigs: RouteConfig[]) {
this.dependencyGraph = dependencyGraph;
this.routeConfigs = routeConfigs;
}
async generateManifest(): Promise<RouteStyleManifest[]> {
const manifests: RouteStyleManifest[] = [];
for (const route of this.routeConfigs) {
const manifest = await this.analyzeRoute(route);
manifests.push(manifest);
}
return manifests;
}
private async analyzeRoute(route: RouteConfig): Promise<RouteStyleManifest> {
const componentTree = await this.buildComponentTree(route);
const aggregatedStyles = await this.aggregateStyles(componentTree);
const { critical, deferred } = await this.categorizeSelectors(aggregatedStyles);
return {
route: route.path,
componentTree,
aggregatedStyles,
criticalSelectors: critical,
deferredSelectors: deferred,
estimatedCriticalSize: this.estimateSize(critical)
};
}
private async categorizeSelectors(styles: AggregatedStyle[]): Promise<{
critical: string[];
deferred: string[];
}> {
const critical = new Set<string>();
const deferred = new Set<string>();
for (const style of styles) {
for (const selector of style.selectors) {
// Heuristics for critical vs deferred
const isCritical = this.isSelectorCritical(selector);
if (isCritical) {
critical.add(selector);
} else {
deferred.add(selector);
}
}
}
return { critical: [...critical], deferred: [...deferred] };
}
private isSelectorCritical(selector: string): boolean {
// Above-the-fold heuristics
const criticalPatterns = [
/^html$/,
/^body$/,
/^header$/,
/^nav$/,
/^main\s*$/,
/\.container$/,
/\.wrapper$/,
/^h[1-6]$/,
/\.[a-z]*hero/i,
/\.[a-z]*header/i,
/\.[a-z]*nav/i
];
return criticalPatterns.some(pattern => pattern.test(selector));
}
}
Phase 2: Critical CSS Extraction Pipeline
2.1 Coverage-Based Critical CSS Extractor
// extraction/critical-extractor.ts
import puppeteer, { Browser, Page } from 'puppeteer';
import { JSDOM } from 'jsdom';
import * as postcss from 'postcss';
interface CriticalExtractionResult {
route: string;
criticalCSS: string;
deferredCSS: string;
coverage: {
usedSelectors: string[];
unusedSelectors: string[];
coveragePercentage: number;
};
viewportVariants: ViewportVariantResult[];
}
interface ViewportVariantResult {
viewport: { width: number; height: number };
criticalSelectors: string[];
renderedHTML: string;
}
export class CriticalCSSExtractor {
private browser: Browser;
private viewports = [
{ width: 320, height: 568 }, // Mobile
{ width: 768, height: 1024 }, // Tablet
{ width: 1280, height: 800 }, // Desktop
{ width: 1920, height: 1080 } // Large Desktop
];
async initialize(): Promise<void> {
this.browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
}
async extractCriticalCSS(
route: string,
fullCSS: string,
htmlContent: string
): Promise<CriticalExtractionResult> {
const page = await this.browser.newPage();
// Enable CSS coverage
await page.coverage.startCSSCoverage();
// Set up content with full CSS
await page.setContent(this.injectCSS(htmlContent, fullCSS), {
waitUntil: 'networkidle0'
});
// Collect coverage
const coverage = await page.coverage.stopCSSCoverage();
// Extract critical ranges
const criticalRanges = this.extractCriticalRanges(coverage);
const criticalCSS = this.extractRangesFromCSS(fullCSS, criticalRanges);
// Multi-viewport analysis
const viewportVariants = await this.analyzeViewports(page, route, fullCSS);
// Merge viewport-specific critical selectors
const allCriticalSelectors = this.mergeViewportSelectors(viewportVariants);
await page.close();
// Generate deferred CSS
const deferredCSS = this.generateDeferredCSS(fullCSS, allCriticalSelectors);
return {
route,
criticalCSS,
deferredCSS,
coverage: {
usedSelectors: allCriticalSelectors,
unusedSelectors: this.findUnusedSelectors(fullCSS, allCriticalSelectors),
coveragePercentage: this.calculateCoverage(fullCSS, criticalCSS)
},
viewportVariants
};
}
private extractCriticalRanges(coverage: any[]): Array<{ start: number; end: number }> {
const ranges: Array<{ start: number; end: number }> = [];
for (const entry of coverage) {
for (const range of entry.ranges) {
ranges.push({
start: range.start,
end: range.end
});
}
}
return this.mergeRanges(ranges);
}
private mergeRanges(ranges: Array<{ start: number; end: number }>): Array<{ start: number; end: number }> {
if (ranges.length === 0) return ranges;
ranges.sort((a, b) => a.start - b.start);
const merged: Array<{ start: number; end: number }> = [ranges[0]];
for (let i = 1; i < ranges.length; i++) {
const last = merged[merged.length - 1];
const current = ranges[i];
if (current.start <= last.end) {
last.end = Math.max(last.end, current.end);
} else {
merged.push(current);
}
}
return merged;
}
private extractRangesFromCSS(css: string, ranges: Array<{ start: number; end: number }>): string {
const extracted: string[] = [];
for (const range of ranges) {
extracted.push(css.substring(range.start, range.end));
}
return extracted.join('\n');
}
private async analyzeViewports(
page: Page,
route: string,
fullCSS: string
): Promise<ViewportVariantResult[]> {
const results: ViewportVariantResult[] = [];
for (const viewport of this.viewports) {
await page.setViewport(viewport);
await page.reload({ waitUntil: 'networkidle0' });
// Force style recalculation
await page.evaluate(() => {
void document.documentElement.offsetHeight;
});
const renderedHTML = await page.content();
// Extract visible selectors
const criticalSelectors = await page.evaluate(() => {
const visible = new Set<string>();
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT
);
let node: Element | null;
while ((node = walker.nextNode() as Element)) {
const rect = node.getBoundingClientRect();
if (rect.top < window.innerHeight) {
node.classList.forEach(cls => visible.add(`.${cls}`));
if (node.id) visible.add(`#${node.id}`);
}
}
return [...visible];
});
results.push({
viewport,
criticalSelectors,
renderedHTML
});
}
return results;
}
private generateDeferredCSS(fullCSS: string, criticalSelectors: string[]): string {
const ast = postcss.parse(fullCSS);
const deferredRules: postcss.Rule[] = [];
ast.walkRules(rule => {
const isCritical = rule.selectors.some(sel =>
criticalSelectors.includes(sel)
);
if (!isCritical) {
deferredRules.push(rule);
}
});
// Build deferred CSS AST
const deferredAST = postcss.root();
deferredRules.forEach(rule => {
deferredAST.append(rule.clone());
});
return deferredAST.toString();
}
async cleanup(): Promise<void> {
await this.browser.close();
}
}
2.2 AST-Based CSS Optimizer
// extraction/css-optimizer.ts
import * as postcss from 'postcss';
import * as cssnano from 'cssnano';
import * as autoprefixer from 'autoprefixer';
import { PurgeCSS } from 'purgecss';
interface OptimizationResult {
original: string;
optimized: string;
removedRules: string[];
minifiedSize: number;
compressionRatio: number;
}
export class CSSOptimizer {
private purgeOptions = {
content: [],
css: [],
safelist: {
standard: [
/^html$/,
/^body$/,
/\[data-/,
/:root/
],
deep: [],
greedy: []
}
};
async optimizeCSS(
css: string,
htmlContent: string,
options: { minify: boolean; purge: boolean }
): Promise<OptimizationResult> {
let result = css;
const removedRules: string[] = [];
// Step 1: Purge unused CSS
if (options.purge) {
const purgeResult = await this.purgeUnusedCSS(result, htmlContent);
result = purgeResult.css;
removedRules.push(...purgeResult.removed);
}
// Step 2: PostCSS transformations
result = await this.applyPostCSS(result);
// Step 3: Minification
if (options.minify) {
result = await this.minifyCSS(result);
}
return {
original: css,
optimized: result,
removedRules,
minifiedSize: Buffer.byteLength(result, 'utf-8'),
compressionRatio: result.length / css.length
};
}
private async purgeUnusedCSS(
css: string,
html: string
): Promise<{ css: string; removed: string[] }> {
const purgeCSS = new PurgeCSS();
const result = await purgeCSS.purge({
content: [{ raw: html, extension: 'html' }],
css: [{ raw: css }],
safelist: this.purgeOptions.safelist,
rejected: true
});
return {
css: result[0].css,
removed: (result[0] as any).rejected || []
};
}
private async applyPostCSS(css: string): Promise<string> {
const result = await postcss([autoprefixer]).process(css, {
from: undefined
});
return result.css;
}
private async minifyCSS(css: string): Promise<string> {
const result = await postcss([
cssnano({
preset: ['advanced', {
discardComments: { removeAll: true },
normalizeWhitespace: true,
colormin: true,
reduceIdents: false,
zindex: false
}]
})
]).process(css, { from: undefined });
return result.css;
}
}
Phase 3: Streaming Hydration Integration
3.1 Progressive CSS Loader
// streaming/progressive-loader.ts
interface CSSChunk {
id: string;
content: string;
priority: 'critical' | 'high' | 'low';
dependencies: string[];
routeScope: string[];
}
interface LoadingStrategy {
chunkId: string;
trigger: 'immediate' | 'preload' | 'idle' | 'interaction' | 'viewport';
conditions?: LoadingCondition[];
}
interface LoadingCondition {
type: 'viewport' | 'scroll' | 'interaction' | 'time';
value: any;
}
export class ProgressiveCSSLoader {
private loadedChunks: Set<string> = new Set();
private loadingPromises: Map<string, Promise<void>> = new Map();
private observerRegistry: Map<string, IntersectionObserver> = new Map();
constructor(
private chunkManifest: Map<string, CSSChunk>,
private strategies: Map<string, LoadingStrategy>
) {
this.initializeLoader();
}
private initializeLoader(): void {
// Load critical chunks immediately
this.loadCriticalChunks();
// Set up preloading
this.setupPreloading();
// Register for streaming hydration events
this.registerHydrationHooks();
}
private loadCriticalChunks(): void {
for (const [id, strategy] of this.strategies) {
if (strategy.trigger === 'immediate') {
this.loadChunk(id);
}
}
}
private setupPreloading(): void {
// Use requestIdleCallback for low-priority chunks
if ('requestIdleCallback' in window) {
requestIdleCallback(() => {
this.loadIdleChunks();
}, { timeout: 2000 });
} else {
setTimeout(() => this.loadIdleChunks(), 1000);
}
// Preload high-priority chunks
for (const [id, strategy] of this.strategies) {
if (strategy.trigger === 'preload') {
this.preloadChunk(id);
}
}
}
async loadChunk(chunkId: string): Promise<void> {
if (this.loadedChunks.has(chunkId)) {
return;
}
if (this.loadingPromises.has(chunkId)) {
return this.loadingPromises.get(chunkId)!;
}
const promise = this.loadChunkInternal(chunkId);
this.loadingPromises.set(chunkId, promise);
return promise;
}
private async loadChunkInternal(chunkId: string): Promise<void> {
const chunk = this.chunkManifest.get(chunkId);
if (!chunk) return;
// Load dependencies first
await Promise.all(chunk.dependencies.map(dep => this.loadChunk(dep)));
// Inject CSS
const styleElement = document.createElement('style');
styleElement.id = `css-chunk-${chunkId}`;
styleElement.textContent = chunk.content;
// Use CSSOM for synchronous injection
document.head.appendChild(styleElement);
this.loadedChunks.add(chunkId);
this.loadingPromises.delete(chunkId);
// Emit load event
this.emitLoadEvent(chunkId);
}
private preloadChunk(chunkId: string): void {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'style';
link.href = this.getChunkURL(chunkId);
document.head.appendChild(link);
}
setupViewportTrigger(chunkId: string, selector: string): void {
const element = document.querySelector(selector);
if (!element) return;
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.loadChunk(chunkId);
observer.disconnect();
}
});
},
{ rootMargin: '50px' }
);
observer.observe(element);
this.observerRegistry.set(chunkId, observer);
}
setupInteractionTrigger(chunkId: string, eventType: string, selector: string): void {
const elements = document.querySelectorAll(selector);
const handler = (event: Event) => {
this.loadChunk(chunkId);
elements.forEach(el => el.removeEventListener(eventType, handler));
};
elements.forEach(el => el.addEventListener(eventType, handler, { once: true }));
}
private loadIdleChunks(): void {
for (const [id, strategy] of this.strategies) {
if (strategy.trigger === 'idle' && !this.loadedChunks.has(id)) {
this.loadChunk(id);
}
}
}
private registerHydrationHooks(): void {
// Listen for streaming hydration events
document.addEventListener('react-hydration-complete', ((event: CustomEvent) => {
const { componentId } = event.detail;
this.onHydrationComplete(componentId);
}) as EventListener);
}
private onHydrationComplete(componentId: string): void {
// Load CSS for newly hydrated components
for (const [chunkId, chunk] of this.chunkManifest) {
if (chunk.routeScope.includes(componentId) && !this.loadedChunks.has(chunkId)) {
this.loadChunk(chunkId);
}
}
}
private emitLoadEvent(chunkId: string): void {
document.dispatchEvent(new CustomEvent('css-chunk-loaded', {
detail: { chunkId }
}));
}
private getChunkURL(chunkId: string): string {
return `/assets/css/${chunkId}.css`;
}
cleanup(): void {
this.observerRegistry.forEach(observer => observer.disconnect());
this.observerRegistry.clear();
}
}
3.2 Streaming CSS Renderer
// streaming/streaming-renderer.ts
import { Writable } from 'stream';
import { RenderToPipeableStreamOptions, renderToPipeableStream } from 'react-dom/server';
interface StreamingCSSConfig {
route: string;
criticalCSS: string;
deferredChunks: Map<string, string>;
preloadChunks: string[];
}
interface StreamState {
criticalInjected: boolean;
shellRendered: boolean;
hydrationReady: boolean;
completedChunks: number;
}
export class StreamingCSSRenderer {
private config: StreamingCSSConfig;
private state: StreamState;
constructor(config: StreamingCSSConfig) {
this.config = config;
this.state = {
criticalInjected: false,
shellRendered: false,
hydrationReady: false,
completedChunks: 0
};
}
createRenderStream(
res: Writable,
App: React.ComponentType,
options: Partial<RenderToPipeableStreamOptions> = {}
) {
const streamOptions: RenderToPipeableStreamOptions = {
bootstrapScripts: [
'/src/entry-client.tsx',
'/src/css-runtime.ts'
],
bootstrapModules: [],
onShellReady: () => {
this.state.shellRendered = true;
this.onShellReady(res);
},
onShellError: (error) => {
this.onShellError(res, error);
},
onAllReady: () => {
this.onAllReady(res);
},
onError: (error) => {
console.error('Streaming error:', error);
},
...options
};
return renderToPipeableStream(<App />, streamOptions);
}
private onShellReady(res: Writable): void {
// Start streaming response
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Transfer-Encoding': 'chunked',
'Cache-Control': 'public, max-age=0, must-revalidate'
});
// Write document start with critical CSS
this.writeDocumentStart(res);
}
private onShellError(res: Writable, error: Error): void {
res.writeHead(500, { 'Content-Type': 'text/html' });
res.end(`<html><body>Error: ${error.message}</body></html>`);
}
private onAllReady(res: Writable): void {
// Write deferred CSS loader script
this.writeDeferredLoader(res);
// Write document end
this.writeDocumentEnd(res);
res.end();
}
private writeDocumentStart(res: Writable): void {
res.write(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>App</title>
<!-- Critical CSS - Inline -->
<style id="critical-css">${this.config.criticalCSS}</style>
<!-- Preload high-priority chunks -->
${this.generatePreloadTags()}
<!-- CSS Runtime Configuration -->
<script id="css-config" type="application/json">
${JSON.stringify({
route: this.config.route,
chunks: Object.fromEntries(this.config.deferredChunks),
preload: this.config.preloadChunks
})}
</script>
</head>
<body>
<div id="root">
`);
}
private generatePreloadTags(): string {
return this.config.preloadChunks
.map(chunkId => {
const url = `/assets/css/chunk-${chunkId}.css`;
return `<link rel="preload" href="${url}" as="style" onload="this.rel='stylesheet'">`;
})
.join('\n');
}
private writeDeferredLoader(res: Writable): void {
res.write(`
<script>
// Progressive CSS Loading Runtime
(function() {
const config = JSON.parse(document.getElementById('css-config').textContent);
// Load deferred chunks progressively
const loadDeferredChunk = (chunkId) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/assets/css/chunk-' + chunkId + '.css';
document.head.appendChild(link);
};
// Load chunks after hydration
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
Object.keys(config.chunks).forEach(loadDeferredChunk);
}, 100);
});
} else {
setTimeout(() => {
Object.keys(config.chunks).forEach(loadDeferredChunk);
}, 100);
}
})();
</script>
`);
}
private writeDocumentEnd(res: Writable): void {
res.write(`
</div>
</body>
</html>
`);
}
}
Phase 4: Build System Integration
4.1 Vite Plugin for CSS Extraction
// build/vite-plugin.ts
import { Plugin, ResolvedConfig, Rollup } from 'vite';
import { CSSDependencyGraph } from '../css-analyzer/dependency-graph';
import { RouteStyleAggregator } from '../css-analyzer/route-aggregator';
import { CriticalCSSExtractor } from '../extraction/critical-extractor';
import { CSSOptimizer } from '../extraction/css-optimizer';
interface PluginOptions {
routes: RouteConfig[];
viewports: ViewportConfig[];
extractionMode: 'build' | 'dev' | 'hybrid';
streaming: boolean;
}
export function criticalCSSPlugin(options: PluginOptions): Plugin {
let config: ResolvedConfig;
let dependencyGraph: CSSDependencyGraph;
let routeAggregator: RouteStyleAggregator;
let extractor: CriticalCSSExtractor;
let optimizer: CSSOptimizer;
return {
name: 'critical-css-extraction',
enforce: 'post',
configResolved(resolvedConfig) {
config = resolvedConfig;
dependencyGraph = new CSSDependencyGraph(resolvedConfig.root + '/tsconfig.json');
routeAggregator = new RouteStyleAggregator(dependencyGraph, options.routes);
optimizer = new CSSOptimizer();
},
async buildStart() {
await dependencyGraph.buildGraph(['src/**/*.tsx', 'src/**/*.ts']);
const manifest = await routeAggregator.generateManifest();
// Store manifest for later use
this.emitFile({
type: 'asset',
fileName: 'css-manifest.json',
source: JSON.stringify(manifest, null, 2)
});
},
async generateBundle(_options, bundle) {
if (options.extractionMode === 'build') {
await this.extractAndBundleCSS(bundle);
}
},
async transformIndexHtml(html, ctx) {
if (!ctx.route) return html;
const routePath = ctx.route;
const manifest = await this.getRouteManifest(routePath);
if (!manifest) return html;
// Inject critical CSS
const criticalCSS = await this.getCriticalCSS(routePath);
return html.replace(
'</head>',
`<style id="critical-css">${criticalCSS}</style></head>`
);
},
handleHotUpdate({ file, server }) {
if (file.endsWith('.css') || file.endsWith('.scss')) {
// Re-extract critical CSS for affected routes
this.reextractAffectedRoutes(file, server);
}
},
async extractAndBundleCSS(bundle: Rollup.OutputBundle) {
extractor = new CriticalCSSExtractor();
await extractor.initialize();
// Extract CSS from bundle
const cssAssets = Object.values(bundle)
.filter(asset => asset.type === 'asset' && asset.fileName.endsWith('.css'));
for (const asset of cssAssets) {
const source = (asset as Rollup.OutputAsset).source as string;
for (const route of options.routes) {
const result = await extractor.extractCriticalCSS(
route.path,
source,
await this.renderRouteHTML(route)
);
// Emit critical CSS chunk
this.emitFile({
type: 'asset',
fileName: `css/critical-${this.sanitizeRouteName(route.path)}.css`,
source: result.criticalCSS
});
// Emit deferred CSS chunk
this.emitFile({
type: 'asset',
fileName: `css/deferred-${this.sanitizeRouteName(route.path)}.css`,
source: result.deferredCSS
});
}
}
await extractor.cleanup();
},
sanitizeRouteName(route: string): string {
return route.replace(/[^a-zA-Z0-9]/g, '-').replace(/^-+|-+$/g, '');
}
};
}
4.2 Webpack Plugin Alternative
// build/webpack-plugin.ts
import { Compiler, Compilation, sources } from 'webpack';
import { CriticalCSSExtractor } from '../extraction/critical-extractor';
export class CriticalCSSWebpackPlugin {
private extractor: CriticalCSSExtractor;
constructor(private options: PluginOptions) {
this.extractor = new CriticalCSSExtractor();
}
apply(compiler: Compiler) {
compiler.hooks.thisCompilation.tap('CriticalCSSPlugin', (compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: 'CriticalCSSPlugin',
stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE
},
async (assets) => {
await this.processAssets(compilation, assets);
}
);
});
}
private async processAssets(compilation: Compilation, assets: Record<string, sources.Source>) {
await this.extractor.initialize();
const cssAssets = Object.keys(assets).filter(name => name.endsWith('.css'));
for (const assetName of cssAssets) {
const source = assets[assetName].source().toString();
for (const route of this.options.routes) {
const result = await this.extractor.extractCriticalCSS(
route.path,
source,
await this.renderRouteHTML(route)
);
// Add critical CSS asset
compilation.emitAsset(
`css/critical-${this.sanitizeRouteName(route.path)}.css`,
new sources.RawSource(result.criticalCSS)
);
// Add deferred CSS asset
compilation.emitAsset(
`css/deferred-${this.sanitizeRouteName(route.path)}.css`,
new sources.RawSource(result.deferredCSS)
);
}
}
await this.extractor.cleanup();
}
}
Phase 5: Client-Side Runtime
5.1 Hydration Coordinator
// client/hydration-coordinator.ts
import { ProgressiveCSSLoader } from './progressive-loader';
interface HydrationState {
route: string;
hydratedComponents: Set<string>;
pendingComponents: Set<string>;
cssLoaded: Set<string>;
errors: Error[];
}
export class HydrationCoordinator {
private state: HydrationState;
private cssLoader: ProgressiveCSSLoader;
private observer: PerformanceObserver;
constructor(route: string, cssManifest: Map<string, CSSChunk>) {
this.state = {
route,
hydratedComponents: new Set(),
pendingComponents: new Set(),
cssLoaded: new Set(),
errors: []
};
this.cssLoader = new ProgressiveCSSLoader(cssManifest, new Map());
this.setupPerformanceMonitoring();
this.registerHydrationHooks();
}
private setupPerformanceMonitoring(): void {
this.observer = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.name.includes('hydration')) {
this.recordHydrationMetric(entry);
}
});
});
this.observer.observe({ entryTypes: ['measure', 'mark'] });
}
private registerHydrationHooks(): void {
// Listen for component hydration events
document.addEventListener('react-hydration-start', ((event: CustomEvent) => {
const { componentId, requiredCSS } = event.detail;
this.onHydrationStart(componentId, requiredCSS);
}) as EventListener);
document.addEventListener('react-hydration-complete', ((event: CustomEvent) => {
const { componentId } = event.detail;
this.onHydrationComplete(componentId);
}) as EventListener);
document.addEventListener('react-hydration-error', ((event: CustomEvent) => {
const { componentId, error } = event.detail;
this.onHydrationError(componentId, error);
}) as EventListener);
}
private async onHydrationStart(componentId: string, requiredCSS: string[]): Promise<void> {
this.state.pendingComponents.add(componentId);
// Ensure CSS is loaded before hydration
await Promise.all(requiredCSS.map(chunk => this.cssLoader.loadChunk(chunk)));
// Signal that CSS is ready
document.dispatchEvent(new CustomEvent('css-ready', {
detail: { componentId }
}));
}
private onHydrationComplete(componentId: string): void {
this.state.hydratedComponents.add(componentId);
this.state.pendingComponents.delete(componentId);
// Check if all components are hydrated
if (this.state.pendingComponents.size === 0) {
this.onAllHydrated();
}
}
private onHydrationError(componentId: string, error: Error): void {
this.state.errors.push(error);
console.error(`Hydration error for ${componentId}:`, error);
}
private onAllHydrated(): void {
// Load remaining CSS chunks
this.cssLoader.loadIdleChunks();
// Report metrics
this.reportHydrationMetrics();
}
private recordHydrationMetric(entry: PerformanceEntry): void {
// Send to analytics
console.log('Hydration metric:', entry.name, entry.duration);
}
private reportHydrationMetrics(): void {
const metrics = {
route: this.state.route,
hydratedCount: this.state.hydratedComponents.size,
errorCount: this.state.errors.length,
cssChunksLoaded: this.state.cssLoaded.size
};
// Send to analytics
if ('sendBeacon' in navigator) {
navigator.sendBeacon('/api/metrics/hydration', JSON.stringify(metrics));
}
}
cleanup(): void {
this.observer.disconnect();
this.cssLoader.cleanup();
}
}
5.2 CSS-Driven Component Loading
// client/css-driven-loader.ts
interface ComponentLoadStrategy {
componentId: string;
cssDependency: string;
loadTrigger: 'visible' | 'interaction' | 'idle' | 'custom';
priority: 'high' | 'medium' | 'low';
}
export class CSSDrivenComponentLoader {
private loadedComponents: Set<string> = new Set();
private loadingComponents: Set<string> = new Set();
private strategies: Map<string, ComponentLoadStrategy>;
private intersectionObserver: IntersectionObserver;
constructor(strategies: ComponentLoadStrategy[]) {
this.strategies = new Map(strategies.map(s => [s.componentId, s]));
this.intersectionObserver = this.createObserver();
}
private createObserver(): IntersectionObserver {
return new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const componentId = (entry.target as HTMLElement).dataset.componentId;
if (componentId && this.strategies.get(componentId)?.loadTrigger === 'visible') {
this.loadComponent(componentId);
}
}
});
},
{ rootMargin: '200px' }
);
}
async loadComponent(componentId: string): Promise<void> {
if (this.loadedComponents.has(componentId) || this.loadingComponents.has(componentId)) {
return;
}
const strategy = this.strategies.get(componentId);
if (!strategy) return;
this.loadingComponents.add(componentId);
// Load CSS first
await this.loadCSS(strategy.cssDependency);
// Then load component
await this.loadComponentModule(componentId);
this.loadingComponents.delete(componentId);
this.loadedComponents.add(componentId);
}
private async loadCSS(cssChunkId: string): Promise<void> {
return new Promise((resolve) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = `/assets/css/chunk-${cssChunkId}.css`;
link.onload = () => resolve();
link.onerror = () => resolve(); // Resolve anyway to not block
document.head.appendChild(link);
});
}
private async loadComponentModule(componentId: string): Promise<void> {
// Dynamic import of component
const module = await import(`../components/${componentId}`);
// Register with hydration system
document.dispatchEvent(new CustomEvent('component-loaded', {
detail: { componentId, module }
}));
}
observeElement(element: HTMLElement): void {
this.intersectionObserver.observe(element);
}
unobserveElement(element: HTMLElement): void {
this.intersectionObserver.unobserve(element);
}
}
Phase 6: Performance Monitoring
6.1 CSS Performance Tracker
// monitoring/css-performance.ts
interface CSSMetric {
name: string;
value: number;
timestamp: number;
route: string;
breakdown: Record<string, number>;
}
export class CSSPerformanceTracker {
private metrics: CSSMetric[] = [];
private route: string;
constructor(route: string) {
this.route = route;
this.setupPerformanceAPI();
}
private setupPerformanceAPI(): void {
// Track paint timing
if ('PerformanceObserver' in window) {
const paintObserver = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
this.recordMetric(`paint-${entry.name}`, entry.startTime, {
type: entry.entryType
});
});
});
paintObserver.observe({ entryTypes: ['paint'] });
// Track layout shifts
const clsObserver = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.entryType === 'layout-shift' && !(entry as any).hadRecentInput) {
this.recordMetric('layout-shift', (entry as any).value, {
source: (entry as any).sources?.[0]?.node?.nodeName || 'unknown'
});
}
});
});
clsObserver.observe({ entryTypes: ['layout-shift'] });
// Track resource loading
const resourceObserver = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.name.includes('.css')) {
this.recordCSSResourceMetric(entry as PerformanceResourceTiming);
}
});
});
resourceObserver.observe({ entryTypes: ['resource'] });
}
}
private recordCSSResourceMetric(entry: PerformanceResourceTiming): void {
const breakdown = {
dns: entry.domainLookupEnd - entry.domainLookupStart,
tcp: entry.connectEnd - entry.connectStart,
ssl: entry.secureConnectionStart > 0 ? entry.connectEnd - entry.secureConnectionStart : 0,
ttfb: entry.responseStart - entry.requestStart,
download: entry.responseEnd - entry.responseStart,
size: entry.encodedBodySize,
compressed: entry.encodedBodySize !== entry.decodedBodySize
};
this.recordMetric(`css-load-${entry.name.split('/').pop()}`, entry.duration, breakdown);
}
recordMetric(name: string, value: number, breakdown: Record<string, any> = {}): void {
this.metrics.push({
name,
value,
timestamp: Date.now(),
route: this.route,
breakdown
});
}
getMetrics(): CSSMetric[] {
return [...this.metrics];
}
generateReport(): CSSPerformanceReport {
const criticalPathMetrics = this.metrics.filter(m =>
m.name.includes('critical') || m.name.includes('paint')
);
const deferredMetrics = this.metrics.filter(m =>
m.name.includes('deferred') || m.name.includes('lazy')
);
return {
route: this.route,
totalCSSLoadTime: this.calculateTotalLoadTime(),
criticalPathTime: this.calculateCriticalPathTime(),
layoutShiftScore: this.calculateLayoutShiftScore(),
metrics: {
critical: criticalPathMetrics,
deferred: deferredMetrics,
all: this.metrics
},
recommendations: this.generateRecommendations()
};
}
private calculateTotalLoadTime(): number {
return this.metrics
.filter(m => m.name.includes('css-load'))
.reduce((sum, m) => sum + m.value, 0);
}
private calculateCriticalPathTime(): number {
const fcp = this.metrics.find(m => m.name === 'paint-first-contentful-paint');
return fcp?.value || 0;
}
private calculateLayoutShiftScore(): number {
return this.metrics
.filter(m => m.name === 'layout-shift')
.reduce((sum, m) => sum + m.value, 0);
}
private generateRecommendations(): string[] {
const recommendations: string[] = [];
const criticalPathTime = this.calculateCriticalPathTime();
if (criticalPathTime > 1000) {
recommendations.push('Critical CSS is taking too long. Consider reducing critical selectors.');
}
const layoutShiftScore = this.calculateLayoutShiftScore();
if (layoutShiftScore > 0.1) {
recommendations.push('High layout shift detected. Review deferred CSS loading strategy.');
}
return recommendations;
}
}
Phase 7: Implementation Timeline
Week 1: Foundation
Week 2: Extraction
Week 3: Streaming Integration
Week 4: Runtime & Monitoring
Week 5: Testing & Optimization
This comprehensive plan provides a complete solution for extracting per-route critical CSS with streaming hydration support, optimizing both initial load performance and progressive enhancement.