A markdown preview that supports maths, diagrams and code highlighting has a weight problem. KaTeX, Mermaid and highlight.js together are far bigger than the markdown parser, and most documents use none of them. A plain README should not pay for a diagram library it never draws.
This article walks through one way to structure a browser-side render pipeline so each of these libraries loads only when a document needs it, and one highlight.js language at a time. The code is simplified from a working app, linked at the end.
Split rendering into two passes
The trick that makes lazy loading easy is to stop treating "render markdown" as one synchronous step:
- Parse pass, synchronous.
markedturns markdown into HTML. Anything that needs a heavy library is left as a cheap placeholder element: a<span class="mdmath">holding the raw TeX, a<div class="mermaid">holding the diagram source, a<code class="language-python">. - Enhancement pass, async, after the HTML is in the DOM. Look for placeholders. Only if some exist,
import()the library and upgrade them.
const mathNodes = el.querySelectorAll('span.mdmath'); if (mathNodes.length) { pending.push( import('katex').then(({ default: katex }) => { mathNodes.forEach((node) => { node.outerHTML = katex.renderToString(node.textContent ?? '', { displayMode: node.dataset.display === '1', throwOnError: false, trust: false, }); }); }).catch(() => { // offline and never cached: the raw TeX stays visible as text }), ); } Mermaid is the same shape: if (el.querySelector('.mermaid')), then import('mermaid'). The bundler emits each as its own chunk, and a document with no maths never requests KaTeX.
A side benefit: the first paint shows the text straight away. Equations and diagrams fill in a moment later, instead of everything waiting on the slowest library.
highlight.js, one language per chunk
import hljs from 'highlight.js' pulls in every language it ships (190+). The fix is to import the core and register languages yourself:
import hljs from 'highlight.js/lib/core'; // One entry per language, generated by a small script from the // highlight.js package so it stays in sync after an upgrade. const LANGUAGE_LOADERS = { bash: () => import('highlight.js/lib/languages/bash'), python: () => import('highlight.js/lib/languages/python'), xml: () => import('highlight.js/lib/languages/xml'), // ... }; Because each import() has a literal path, the bundler makes one small chunk per language. Then a loader that the highlighting pass awaits for every language the document's fences name:
const loads = new Map(); function ensureLanguage(name) { if (hljs.getLanguage(name)) return Promise.resolve(); if (loads.has(name)) return loads.get(name); const load = LANGUAGE_LOADERS[name]; if (!load) return Promise.resolve(); // unknown language: leave it plain const p = load() .then(({ default: def }) => { hljs.registerLanguage(name, def); const deps = LANGUAGE_DEPS[name] ?? []; return Promise.all(deps.map(ensureLanguage)); }) .catch(() => loads.delete(name)); // retry next time, e.g. back online loads.set(name, p); return p; } Two details in there are easy to miss.
The promise cache. A page with twenty JavaScript fences would otherwise start twenty imports of the same chunk. Caching the in-flight promise makes them share one.
Sub-languages, and the cycle they hide. Some languages embed others: xml highlights <script> contents with javascript, and javascript highlights tagged templates with xml. If the embedded language is not registered, highlight.js quietly renders that region as plain text, with no warning. So each language also loads its dependencies (LANGUAGE_DEPS, generated by the same script).
That creates a cycle: xml waits on javascript, which waits on xml. If each side awaited the other's in-flight promise, neither would resolve. The way out is the order inside .then: register the language first, then load its dependencies. When javascript recurses back into xml, the hljs.getLanguage('xml') check at the top already passes and returns a resolved promise.
Fences with no language. hljs.highlightAuto can only guess among languages already registered. For an unlabelled fence, load a small detection set first (bash, css, go, java, javascript, json and a few others) rather than all of them.
Maths has to be pulled out before markdown runs
You cannot let marked see TeX. It treats _ and * as emphasis and escapes backslashes, so $a_1 * b_2$ arrives mangled. The math has to be taken out first and replaced with a placeholder token, then turned back into a placeholder element after parsing.
But a naive $...$ regex breaks other things:
-
echo $HOMEin a shell snippet - a PHP variable in a code span
- "it costs $5 and $10" in a sentence
So the order is: set code fences and code spans aside first, then look for maths in what is left, then put the code back. For inline maths, use the rule GitHub and Pandoc follow: no space just inside either dollar, and a closing dollar followed by a digit is a price, not maths.
// $...$ with no space inside either dollar, not escaped, // and not followed by a digit ("$5 and $10" stays text) const INLINE_MATH = /(?<![\\$])\$(?=\S)([^\n$]*?[^\s\\$])\$(?!\d)/g; Sanitising, and where the placeholders go
If the preview renders documents from other people (a shared link, an imported URL), the HTML has to go through a sanitiser such as DOMPurify. The order matters here too.
Put the maths placeholder elements in before sanitising, never after. A $...$ can sit inside an HTML attribute in the source. If you splice your own markup in after the sanitiser has run, its quotes can close that attribute and turn the rest into live HTML. Done before, the sanitiser sees everything.
KaTeX and Mermaid output is inserted after the sanitiser, so pin their safe settings explicitly rather than trusting defaults to stay the same across upgrades: trust: false for KaTeX (refuses \href{javascript:...} and the \html* commands), securityLevel: 'strict' for Mermaid.
Making lazy chunks work offline
Lazy chunks have a catch in a PWA: a service worker can only serve from cache what was fetched before. A user who installs the app, goes offline, and then opens their first document with an equation would get raw TeX.
The fix is to warm the chunks once the app is idle:
function warm() { import('mermaid').catch(() => {}); import('katex').catch(() => {}); for (const name of DETECTION_LANGUAGES) ensureLanguage(name); } if ('requestIdleCallback' in window) requestIdleCallback(warm, { timeout: 10_000 }); else setTimeout(warm, 3000); This does not slow the first render, since it runs after it, and the service worker's runtime cache picks the chunks up. Only the detection set of languages is warmed. Fetching all 190+ would undo the point of splitting them.
Takeaways
- Render in two passes: synchronous parse with placeholders, then an async enhancement pass that imports libraries only for placeholders it finds.
- Give
import()literal paths so the bundler can split per library and per language. - Cache in-flight promises, and register before recursing into dependencies, or cyclic sub-languages deadlock.
- Take code out before looking for maths, and treat a dollar before a digit as money.
- Insert placeholders before sanitising, and pin the libraries' safe options.
- In a PWA, warm lazy chunks on idle so they work offline.
The code above is simplified from Markdown Preview, a free browser-based markdown editor, where this pipeline renders the preview.
