Created
January 13, 2024 07:24
-
-
Save yusukebe/ac2fe4945beca53f0684a804c83847ab to your computer and use it in GitHub Desktop.
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
async function streamToElement(response: Response, element: HTMLElement) { | |
if (response.body) { | |
const reader = response.body.getReader() | |
const decoder = new TextDecoder('utf-8') | |
while (true) { | |
const { done, value } = await reader.read() | |
if (done) break | |
const text = decoder.decode(value, { stream: true }) | |
const textNode = document.createTextNode(text) | |
element.appendChild(textNode) | |
} | |
} | |
} | |
document.addEventListener('DOMContentLoaded', async (event) => { | |
const response = await fetch('/stream') | |
const root = document.getElementById('root') | |
if (root) { | |
await streamToElement(response, root) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment