Skip to content

Instantly share code, notes, and snippets.

@DylanPiercey
Last active November 20, 2025 14:24
Show Gist options
  • Select an option

  • Save DylanPiercey/21bb73fce3063fb87365454f679e8086 to your computer and use it in GitHub Desktop.

Select an option

Save DylanPiercey/21bb73fce3063fb87365454f679e8086 to your computer and use it in GitHub Desktop.
Streaming with stylesheet links
import http from "node:http";
import timers from "node:timers/promises";
const css = {
"/section1.css":
"body { background: #111; color: #0f0; } .box { border: 2px solid #0f0; } section:nth-of-type(1) .box::before { content: 'Section 1: ' }",
"/section2.css":
"body { color: #0ff; } .box { border-color: #0ff; } section:nth-of-type(2) .box::before { content: 'Section 2: ' }",
"/section3.css":
"body { color: #f0f; } .box { border-color: #f0f; } section:nth-of-type(3) .box::before { content: 'Section 3: ' }",
};
const html = [
`<!doctype html>
<html>
<head>
<title>Streaming + blocking CSS demo</title>
</head>
<body>
<h1>Streaming demo</h1>
<p>Each section has a blocking &lt;link rel="stylesheet"&gt;.</p>
`,
`
<section>
<link rel="stylesheet" blocking="render" href="/section1.css">
<div class="box">should appear after /section1.css loads.</div>
</section>
<script>
console.log("loaded script 1");
document.currentScript.previousElementSibling.append(new Text(" (script 1 loaded)"))
</script>
`,
`
<section>
<link rel="stylesheet" blocking="render" href="/section2.css">
<div class="box">should appear after /section2.css loads.</div>
</section>
<script>
console.log("loaded script 2");
document.currentScript.previousElementSibling.append(new Text(" (script 2 loaded)"))
</script>
`,
`
<section>
<link rel="stylesheet" blocking="render" href="/section3.css">
<div class="box">should appear after /section3.css loads.</div>
</section>
<script>
console.log("loaded script 3");
document.currentScript.previousElementSibling.append(new Text(" (script 3 loaded)"))
</script>
`,
`
</body>
</html>
`
];
const server = http.createServer(async (req, res) => {
if (css[req.url]) {
const assetIndex = parseInt(req.url.replace(/\D/g, ""), 10);
await timers.setTimeout(1000 * assetIndex);
res.writeHead(200, { "Content-Type": "text/css" });
res.end(css[req.url]);
} else {
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Transfer-Encoding": "chunked",
});
res.write(html[0]);
for (const chunk of html.slice(1, -1)) {
await timers.setTimeout(500);
res.write(chunk);
}
res.end(html[html.length - 1]);
}
});
server.listen(3000, () => {
console.log("http://localhost:3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment