Skip to content

Instantly share code, notes, and snippets.

@peat-psuwit
Created April 23, 2024 07:06
Show Gist options
  • Save peat-psuwit/53a0b13dfda8781ac34cf6e66cc92ec0 to your computer and use it in GitHub Desktop.
Save peat-psuwit/53a0b13dfda8781ac34cf6e66cc92ec0 to your computer and use it in GitHub Desktop.
streamingHTML
import { setTimeout } from "node:timers/promises";
import express from "express";
/* Simple HTML streaming concept, inspired by now NextJS do it, but without React.
* TODO: figure out why in the world does Firefox not show the "Loading..." as soon
* as it's received.
*/
async function getContent() {
await setTimeout(5000);
return {
id: "main-content",
innerHTML: "<h1>Hello, world!</h1>",
};
}
const app = express();
app.get("/", async (req, res) => {
res.status(200);
// TODO: maybe de-indent.
res.write(`
<!DOCTYPE html>
<html>
<head>
<title>Hello, world</title>
</head>
<body>
<div id="main-content">Loading...</div>
`);
let content = await getContent();
res.write(`
<script>
document.getElementById(${JSON.stringify(content.id)}).innerHTML = ${JSON.stringify(content.innerHTML)};
</script>
`);
res.write(`
</body>
</html>
`);
res.end();
});
console.log("http://localhost:3000");
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment