“My Attention Dies In Darkness”

Adding Math with Zero JavaScript

how to add math to your website without adding the kilos

2 min read

Preamble

My site is rather lightweight, weighing only about 2kb over the wirehttps://radar.cloudflare.com/scan/727f36b6-d340-43e9-a392-bd6862e9b847/summary. So, the usual ways of bringing math to the front end such as KaTeX or LaTeX alone would eclipse the total size of my blog. So, I would have to either optimize KaTeX to be more lightweight or find an alternative to bring math.

It turns out that the alternative is already prebaked into your browser.

What’s MathML

MathML is a XML specification used to write TeX like mathematical formulae. Compatibility is paramount. MathML is Widely Available in Baseline so 93% of all web users can use it making it virtually universal for all intents and purposes.

Benefits of using MathML over KaTeX

lowkey, now if i think about it, you could just tree shake or something the stylesheets 💀💀💀💀💀

KaTeX is a fabulous project made by great people but even when prerendered, requires fonts, which are seldom bundled natively in browsers and my blog specifically doesn’t use external fonts to maintain the performance it has. Furthermore, it has external stylesheets, which is something I usually want to avoid.

MathML is a feature in your web browser so it has zero JavaScript runtime, zero external stylesheets with minimal visual differences with LaTeX or KaTeX (although in modern browsers the difference is getting smaller). It may have minor visual differences with KaTeX but it doesn’t look bad at all.

Examples

Euler’s

eix=cosx+isinxe^{ix} = \cos x + i\sin x

Gaussian

0ex2dx=π2\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}

How To Use It

“Thou shalt Google.”

I use astro for my site so I can’t say anything about any other frameworks, but I suppose you may consult Google.

  • Install @astrojs/markdown-remark via your preferred package manager.
  • Also install remark-math
  • Also install rehype-katex

As my examples may become outdated as time goes on so it would be wise to consult the Astro documentation for Rehype/Remark.

// @ts-check
import { defineConfig } from "astro/config";

import { unified } from "@astrojs/markdown-remark";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";

import sitemap from "@astrojs/sitemap";

// https://astro.build/config
export default defineConfig({
  devToolbar: {
    enabled: false,
  },

  site: "https://undefinedfile.pages.dev/",
  integrations: [sitemap()],

  markdown: {
    remarkPlugins: [remarkMath],
    rehypePlugins: [[rehypeKatex, { output: "mathml" }]],
  },
});

Here we have

...
{
    rehypePlugins: [[rehypeKatex, {output: 'mathml'}]]
}

to tell rehype-katex to output MathML instead of KaTeX.