Sub topic 11
Rendering partial output in the UI
Earlier chapters showed how deltas arrive and how to accumulate them into a message. This chapter covers the last step: getting that growing text onto the screen without flicker, wasted work, or security holes. It assumes you can read the fetch streaming client from the browser chapter, know basic DOM APIs, and have seen Markdown in chat interfaces.
What the UI has to do
A streamed answer is a document that changes many times per second. A chat UI has to do four things with it:
- Show new text as soon as it arrives.
- Keep the newest text in view, unless the user has scrolled away.
- Avoid repeating work, such as re-rendering the whole message on every token.
- Treat model output as untrusted input.
Tokens often arrive faster than a screen refreshes, which is usually 60 times per second or less. Some providers send several tokens per event, and a fast model can send dozens of events per second. Updating the DOM for each one gains nothing, because the browser only paints once per frame.
Batch updates per animation frame
The simplest fix is to collect deltas in a buffer and write them to the page once per frame, using requestAnimationFrame. The network handler stays cheap, and the DOM is touched at most once per frame.
The class below applies this idea to plain text. It appends to a single text node with appendData, so the browser does not rebuild the whole element each time.
class StreamView {
constructor(scroller, target) {
this.scroller = scroller;
this.target = target;
this.textNode = document.createTextNode("");
this.target.appendChild(this.textNode);
this.target.setAttribute("aria-busy", "true");
this.pending = "";
this.scheduled = false;
this.stickToBottom = true;
scroller.addEventListener("scroll", () => {
const distance =
scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;
this.stickToBottom = distance < 40;
});
}
push(delta) {
this.pending += delta;
if (!this.scheduled) {
this.scheduled = true;
requestAnimationFrame(() => this.flush());
}
}
flush() {
this.scheduled = false;
if (this.pending) {
this.textNode.appendData(this.pending);
this.pending = "";
}
if (this.stickToBottom) {
this.scroller.scrollTop = this.scroller.scrollHeight;
}
}
finish() {
this.flush();
this.target.removeAttribute("aria-busy");
}
}To connect it to the earlier client, create one view per assistant message and call push from the onData callback:
const view = new StreamView(
document.querySelector("#chat"),
document.querySelector("#answer")
);
const controller = new AbortController();
streamCompletion(
"/api/chat",
{ prompt: "Hello" },
(data) => {
if (data === "[DONE]") return view.finish();
view.push(JSON.parse(data).delta);
},
controller.signal
).catch(() => view.finish());This assumes the relay sends {"delta": "..."} payloads, as in the earlier parser example. Real provider payloads nest the text deeper, so adapt the field access.
Scrolling without fighting the user
Always forcing the view to the bottom is a common mistake. If the user scrolls up to reread something, the next token drags them back down. The stickToBottom flag fixes this. It stays true while the user is within 40 pixels of the bottom, and turns false once they scroll further up. When they scroll back down, it becomes true again. Many products also show a "Jump to latest" button while the flag is false.
Rendering Markdown while it is incomplete
Plain text is the easy case. Models usually answer in Markdown, and a half-finished stream is often invalid Markdown. Typical problems are an opened code fence with no closing fence, a ** with no partner, and a table with only a header row.
The most reliable approach is to re-render the accumulated string from scratch on each flush, instead of trying to patch HTML incrementally. Parsers are fast enough for chat-sized messages. You can reduce visible glitches with a small repair step before parsing. This helper closes an unterminated code fence so the rest of the page does not turn into a code block:
function closeOpenFence(markdown) {
const fence = "`".repeat(3);
const fenceLines = markdown
.split("\n")
.filter((line) => line.trimStart().startsWith(fence));
return fenceLines.length % 2 === 1 ? markdown + "\n" + fence : markdown;
}Then render with a Markdown library and sanitize the result:
// Assumes the marked and DOMPurify libraries are loaded.
function renderMarkdown(target, fullText) {
const html = marked.parse(closeOpenFence(fullText));
target.innerHTML = DOMPurify.sanitize(html);
}Controlling the cost of re-rendering
Re-parsing the whole message on every frame costs more as the message grows. A 5,000-token answer re-parsed 60 times per second is wasteful. These measures help, in rough order of effort:
- Keep the per-frame batching, so parsing runs at most once per frame.
- Throttle Markdown renders to every 50 to 100 ms. The text still looks continuous.
- Split the message into blocks at blank lines. Render finished blocks once and cache them. Re-parse only the last, still-open block.
- In a framework such as React, keep the streaming message in its own component, so earlier messages do not re-render. Memoize finished messages.
Layout stability and accessibility
Growing text changes layout, so a few details matter:
- Give message containers a sensible minimum height, and avoid inserting content above the viewport while the user reads.
- Add a visible "generating" indicator, such as a blinking cursor, and remove it in
finish(). Also remove it on abort or error, or it will blink forever. - Screen readers can announce every token if you mark the whole stream as a live region. Setting
aria-busy="true"while streaming tells assistive technology to wait. Announce the message once, when streaming ends. Usearia-live="polite"on a container whose content changes only at completion, or on a separate status element.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Page lags on long answers | Full re-render per delta | Batch per frame, throttle, cache finished blocks |
| Rest of page appears as code | Unclosed code fence | Close the fence before parsing |
| User dragged back to bottom | Unconditional auto-scroll | Track a stick-to-bottom flag |
| Cursor never disappears | Cleanup only on success | Call `finish()` on abort and error too |
| Script runs from model output | Unsanitized `innerHTML` | Use `textContent` or sanitize |
| Screen reader reads every token | Live region on a changing node | Use `aria-busy`, announce at completion |
Exercise
A teammate updates the page with answer.innerHTML = fullText inside the delta handler. Name two problems with this and one change that fixes both.
Show answer
First, it runs on every delta, so the browser re-parses and rebuilds the element many times between paints. Second, it inserts untrusted model output as HTML, which allows script injection and also breaks the text if the model writes characters like <. Buffer deltas and flush once per animation frame, writing with textContent or a text node (or sanitized Markdown HTML) instead.
Exercise
The model's reply contains a code block, and midway through streaming the whole rest of the message renders as monospaced code. What causes this, and how would you handle it?
Show answer
The opening code fence has arrived but the closing fence has not, so the Markdown parser treats everything after it as code. Before each render, count the fence lines in the accumulated text. If the count is odd, append a temporary closing fence to the copy you parse. Keep the original text unchanged, so the real fence is handled correctly when it arrives.