Created
April 23, 2024 07:06
-
-
Save peat-psuwit/53a0b13dfda8781ac34cf6e66cc92ec0 to your computer and use it in GitHub Desktop.
streamingHTML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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