1 min read

Auto-rendering Math with KaTeX

Supported Platforms

Web
Node.js
Mobile (via webview)

Setup

1. Add KaTeX and auto-render scripts

Add the following lines to the <head> section of your HTML page:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/katex.min.css" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/katex.min.js" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/contrib/auto-render.min.js" crossorigin="anonymous"
		onload="renderMathInElement(document.body);"></script>

The defer attribute speeds up page loading, and onload triggers auto-rendering as soon as the script is ready.

2. Customizing delimiters (optional)

<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/contrib/auto-render.min.js" crossorigin="anonymous"></script>
<script>
	document.addEventListener("DOMContentLoaded", function() {
		renderMathInElement(document.body, {
			delimiters: [
				{left: '$$', right: '$$', display: true},
				{left: '$', right: '$', display: false},
				{left: '\\(', right: '\\)', display: false},
				{left: '\\[', right: '\\]', display: true}
			],
			throwOnError: false
		});
	});
</script>

3. Import as an ECMAScript module (advanced)

You can also import auto-render as an ECMAScript module:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/katex.min.css" crossorigin="anonymous">
<script type="module">
	import renderMathInElement from "https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/contrib/auto-render.mjs";
	renderMathInElement(document.body);
</script>

4. Other optional configurations

Organization and advanced options

  • Ignore certain elements (like <pre>, <code>, etc.) via the ignoredTags option.
  • Add custom LaTeX macros via the macros option.
  • See the official documentation for all options.