A lightweight, streaming Markdown parser that renders directly into the DOM — character by character, in real time. No dependencies, no build step.
Version: md v4.0.1 Author: Alphons van der Heijden
MarkdownStreamer processes Markdown one character at a time. This makes it ideal for streaming output from an LLM or any character-based text source: the DOM is updated live as characters arrive, with no buffering of the full document required.
<div id="output"></div>
<script src="md4.js"></script>
<script>
const el = document.getElementById('output');
const streamer = new MarkdownStreamer(el);
streamer.markdown('# Hello\n\nThis is **MarkdownStreamer**.');
streamer.finalize();
</script><div id="output"></div>
<script src="md4.js"></script>
<script>
async function stream() {
const el = document.getElementById('output');
const streamer = new MarkdownStreamer(el);
streamer.setSpeed(80); // 1–100, higher = faster
await streamer.markdownasync('# Hello\n\nStreamed **word by word**...');
streamer.finalize();
}
stream();
</script>streamer.stop(); // halts markdownasync() immediately| Method | Description |
|---|---|
new MarkdownStreamer(rootEl) |
Create a new instance. Clears rootEl and attaches the parser. |
markdown(text) |
Render the full text synchronously (instant). |
markdownasync(text) |
Render the text asynchronously with animated streaming. Returns a Promise. |
finalize() |
Flush any remaining state and close open elements. Always call this after rendering. |
setSpeed(n) |
Set streaming speed (1–100). Controls the batch size and delay between frames. |
stop() |
Abort an in-progress markdownasync() call. |
A common pattern is to stream LLM output chunk by chunk using the browser's EventSource API (SSE). Each incoming chunk is fed into markdownasync(). Because chunks arrive asynchronously and out of order, the calls are chained through a Promise so they are always processed sequentially.
var streamer;
let eventSource = new EventSource('/api/Chat/Events');
// Chain incoming chunks so they are rendered in order
let processingPromise = Promise.resolve();
eventSource.onmessage = function (event) {
const text = event.data.replace(/\\n/g, '\n');
processingPromise = processingPromise.then(() => streamer.markdownasync(text));
};When the user sends a message, a new div and MarkdownStreamer are created for the assistant reply, and setSpeed() is tuned for near-real-time output:
async function sendMessage(text) {
// Render the user message instantly
const divUser = document.createElement('div');
divUser.classList.add('user');
const userStreamer = new MarkdownStreamer(divUser);
userStreamer.markdown(text);
userStreamer.finalize();
output.append(divUser);
// Prepare the assistant reply container
const divAssistant = document.createElement('div');
divAssistant.classList.add('assistant');
streamer = new MarkdownStreamer(divAssistant);
streamer.setSpeed(95); // near-real-time
output.append(divAssistant);
// POST to the API — SSE events will drive the streamer above
await fetch('/api/Chat/Say', { method: 'POST', body: JSON.stringify({ text }) });
}Existing chat history (already complete messages) is rendered synchronously with markdown() + finalize():
function renderHistory(messages) {
messages.forEach(item => {
if (item.role === 'system') return;
const div = document.createElement('div');
div.classList.add(item.role); // 'user' or 'assistant'
const s = new MarkdownStreamer(div);
s.markdown(item.content);
s.finalize();
output.append(div);
});
}Key points:
- Use one
MarkdownStreamerinstance per message bubble — do not reuse across messages. - Chain
markdownasync()calls via aPromisewhen chunks arrive concurrently. - Use
markdown()+finalize()for already-complete text (history, user input). setSpeed(95)gives smooth, near-real-time LLM output animation.
# H1
## H2
### H3
#### H4
##### H5
###### H6
Setext H1
=========
Setext H2
---------
## Heading with closing hashes ##| Syntax | Result |
|---|---|
**bold** |
bold |
*italic* |
italic |
__underline__ |
underline |
~~strikethrough~~ |
|
==highlight== |
highlighted |
`inline code` |
inline code |
x^sup^ |
superscript |
H~sub~ |
subscript |
***bold italic*** |
bold italic |
Line one (two trailing spaces)
Line two
Line one\
Line two[label](https://example.com)
[label](https://example.com "title")
<https://example.com> <!-- autolink -->
<info@example.com> <!-- email autolink -->
https://example.com <!-- bare URL (auto-detected) -->
[Google][ref] <!-- reference link -->
[Google] <!-- implicit reference link -->
[ref]: https://www.google.com "optional title"
[](https://example.com)> Level 1
>
> > Level 2
> >
> > > Level 3Unordered:
- Item A
- Item B
- Sub B1
- Sub B2Ordered:
1. First
2. Second
1. Sub 2a
3. Third
1) Alternative style
2) With parenthesesMixed:
- Fruit
1. Apple
2. Pear- [x] Done
- [ ] Open taskFenced (backticks or tildes):
```javascript
function hello() { return 'world'; }
```
~~~css
body { color: red; }
~~~
~~~~
four-tilde fence
~~~~Indented (4 spaces):
this is a code block
indented by 4 spaces| Left | Center | Right |
|:-------|:-------:|------:|
| a | b | 1 |
| **vet**| *cursief*| `code`|Column alignment: :--- left, :---: center, ---: right.
---
***
_ _ _
- - -Markdown
: A lightweight markup language
HTML
: HyperText Markup Language
: The structure language of the webThis has a footnote.[^1]
[^1]: Footnote text here.The HTML spec is used daily.
*[HTML]: HyperText Markup LanguageAbbreviations are automatically wrapped in <abbr title="..."> throughout the document.
Block-level HTML elements are passed through directly:
<details>
<summary>Click to expand</summary>
Hidden content.
</details>Inline HTML comments are also supported:
before <!-- hidden --> after\*not italic\* \`not code\` \[not a link\]Named and numeric entities are decoded:
© & < > € — 😀| File | Description |
|---|---|
tests/md4.js |
The parser — include this in your page |
tests/md4.css |
Full stylesheet for rendered output (dark/light) |
tests/md4-light.css |
Light-theme-only stylesheet |
tests/md4.html |
Interactive demo with live streaming, speed control, and theme toggle |
tests/md4start.js |
Demo wiring (stream/stop buttons, theme toggle) |
Copyright (c) 2025–2026, Alphons van der Heijden. https://github.com/alphons/MarkdownStreamer