Framing the Objective
I'm now fully immersed in understanding the user's core request: a clear, usable code sample showcasing web performance optimization. It's about distilling the core techniques into something immediately practical. I'm focusing on the "how" now, sketching out the structure and deciding which techniques to highlight first.
Structuring the Implementation
Now, I'm fleshing out the HTTP/2 caching header section. I've decided to use an Express.js server to demonstrate setting the headers directly, focusing on Cache-Control directives for static assets. I'm also thinking about incorporating a simple example to show how to invalidate the cache with versioning or content hashes.
Detailing Code Implementation
I'm zeroing in on the code structure. I've got the Express.js server skeleton for caching headers in place. I'm now drafting the React components for code splitting, using React.lazy and Suspense. The Fibonacci number generator will be a good candidate to offload to a web worker. I'm also now thinking of using a small React context for the Fibonacci number.
Expanding Code Snippets
I'm now focused on the worker code, writing the logic for worker.js and connecting it to a component. I'm choosing the Fibonacci sequence calculation for the web worker example and integrating it with React state for a responsive UI. I'm also now thinking on a concise explanation about the worker communication.
Elaborating the Example
I'm now integrating the HTTP/2 headers with a simple Express.js server, and wrapping it with spdy to simulate HTTP/2. I'll outline the file structure and the necessary React components, including HeavyComponent with React.lazy and a worker-powered component using the Fibonacci sequence. The code will include instructions for running it locally.
Integrating Components and Concepts
Now, I'm integrating the Express.js server, React components, and worker scripts. I'm focusing on providing clear, concise examples for HTTP/2 caching, React code splitting with Suspense, and a web worker-powered Fibonacci sequence calculator. I will add comments to explain key decisions, such as using immutable for static assets and the benefit of web workers.
Elaborating on Implementation
The focus is now on the implementation details. I'm actively crafting the Express.js server setup to serve static files with appropriate cache headers and integrating it with spdy. I'm using immutable for static assets and no-cache for HTML. This ensures efficient caching strategies in an HTTP/2 environment. Additionally, I'm working on the React components, including HeavyChart for lazy loading, and the Fibonacci sequence implemented using a web worker to simulate a heavy calculation.
Here is a complete implementation setup demonstrating all three performance techniques.
This example assumes a standard Create React App (CRA) or Vite structure managed by a custom Node.js (Express) server for the HTTP/2 handling.
Project Structure
/root
├── server.js (Part 1: HTTP/2 & Caching)
└── src/
├── App.jsx
├── components/
│ └── HeavyChart.jsx (Part 2: Code Splitting)
└── workers/
└── heavyTask.js (Part 3: Web Workers)
Part 1: HTTP/2 & Caching Headers (Node/Express)
To serve files over HTTP/2 locally, we need the spdy package (or the native http2 module) and a self-signed certificate.
Key Header Strategy:
- HTML:
no-cache (Always check server for updates).
- JS/CSS/Images:
long max-age + immutable (Because bundlers add hashes to filenames, e.g., main.a1b2.js. If the file changes, the name changes, so we can cache the old one forever).
Command to run: npm install express spdy compression
/* server.js */
const spdy = require('spdy');
const express = require('express');
const path = require('path');
const fs = require('fs');
const compression = require('compression');
const app = express();
const PORT = 3000;
// Enable Gzip/Brotli compression (standard best practice)
app.use(compression());
// 1. STATIC ASSETS (JS, CSS, Images)
// Strategy: Long cache, Immutable.
// Explanation: These files usually have hashes in filenames (e.g., app.a1c2.js).
app.use('/static', express.static(path.join(__dirname, 'build/static'), {
setHeaders: (res, path) => {
// HTTP/2 Caching Implementation
// "public": Can be cached by CDN/proxies
// "max-age": 1 year in seconds
// "immutable": Browser never revalidates if file exists in cache
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
// Security headers (Good practice for H2)
res.setHeader('X-Content-Type-Options', 'nosniff');
}
}));
// 2. ROOT HTML
// Strategy: No Cache
// Explanation: We want the browser to verify if index.html has changed so it can
// fetch new hashed references to JS/CSS files.
app.get('*', (req, res) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
// 3. CREATE HTTP/2 SERVER
// Note: H2 requires SSL. We generate self-signed certs for local dev.
const options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
spdy.createServer(options, app).listen(PORT, (error) => {
if (error) {
console.error(error);
return process.exit(1);
}
console.log(`HTTP/2 server listening on port ${PORT}`);
});
Part 2: Code Splitting (React)
We use React.lazy and machine-specific import() to ensure the HeavyChart JavaScript code is not downloaded by the client until the user actually navigates to that view or renders the component.
/* src/components/HeavyChart.jsx */
import React from 'react';
// A dummy heavy component
const HeavyChart = () => {
return (
<div style={{ padding: '20px', border: '2px solid red' }}>
<h2>I am a Heavy Chart</h2>
<p>My javascript code was loaded separately on demand!</p>
</div>
);
};
export default HeavyChart; // Must be default export for React.lazy
/* src/App.jsx (Snippet) */
import React, { useState, Suspense, lazy } from 'react';
// DYNAMIC IMPORT
// This tells Webpack/Vite to create a separate chunk file for this component
const HeavyChart = lazy(() => import('./components/HeavyChart'));
export default function App() {
const [showChart, setShowChart] = useState(false);
return (
<div className="App">
<h1>Performance Demo</h1>
<button onClick={() => setShowChart(true)}>Load Heavy Chart</button>
{/* SUSPENSE BOUNDARY */}
{/* Handles the UI state while the code chunk is downloading */}
{showChart && (
<Suspense fallback={<div>Downloading bundle chunk...</div>}>
<HeavyChart />
</Suspense>
)}
</div>
);
}
Part 3: Web Workers (Background Processing)
Web Workers allow you to run JavaScript on a separate thread. This prevents the UI (Main Thread) from freezing during complex calculations.
1. The Worker File
This runs in an isolated context. It cannot access the DOM.
/* src/workers/heavyTask.js */
// Listen for messages from the main thread
self.onmessage = (e) => {
console.log("Worker: Message received from main thread");
const { number } = e.data;
// Simulate heavy blocking CPU calculation (Fibonacci)
const result = calculateFibonacci(number);
// Send result back to main thread
self.postMessage(result);
};
function calculateFibonacci(num) {
if (num <= 1) return 1;
return calculateFibonacci(num - 1) + calculateFibonacci(num - 2);
}
2. React Integration
Using the worker in a component.
/* src/components/WorkerDemo.jsx */
import React, { useState, useEffect, useRef } from 'react';
export default function WorkerDemo() {
const [status, setStatus] = useState('Idle');
const [result, setResult] = useState(null);
// Use ref to keep track of the worker instance
const workerRef = useRef();
useEffect(() => {
// Initialize the Worker
// 'import.meta.url' ensures the path resolves correctly in ESM modules (Vite/modern Webpack)
workerRef.current = new Worker(new URL('../workers/heavyTask.js', import.meta.url));
// Handle response from worker
workerRef.current.onmessage = (event) => {
setResult(event.data);
setStatus('Done');
console.log("Main: Message received from worker");
};
// Cleanup on unmount
return () => {
workerRef.current.terminate();
};
}, []);
const handleCalculate = () => {
setStatus('Calculating...');
setResult(null);
// Send data to the worker
// If we did this on the main thread, the UI would freeze completely
workerRef.current.postMessage({ number: 40 });
};
return (
<div>
<h2>Web Worker Fibonacci</h2>
<p>Status: {status}</p>
<p>Result: {result}</p>
<button onClick={handleCalculate}>Run Heavy Calculation</button>
{/* Prove the UI isn't frozen by typing here while it calculates */}
<input type="text" placeholder="Type while calculating..." />
</div>
);
}
Summary of Benefits
- HTTP/2 & Caching: The
immutable header tells the browser "Use the cached file, don't even ask the server if it changed." This saves network round-trips. HTTP/2 allows multiple files (like split code chunks) to download in parallel over a single connection.
- Code Splitting:
import() creates a separate .js file (chunk). The initial load of your app becomes much smaller (faster First Contentful Paint) because the user doesn't download the chart code until they click the button.
- Web Workers: If you ran
fibonacci(40) on the main thread, the <input> box in Part 3 would become unresponsive (you couldn't type) until the math finished. By moving it to a worker, the animation and typing remain buttery smooth.