Rendering LaTeX using KaTeX and Jekyll

  06 December 2014  │ 
  LaTeX, Jekyll

So as a Ph.D. student who studies in Computer Science, using LaTeX to render the equations in my blog is inevitable. In general, I hope the render can support the following features:

The most popular way to render LaTeX within Jekyll is using MathJaX. There are lots of blogs (e.g. this) to show you how to configure it. But MathJaX has a huge shortage on rendering speed. It’s slow, not for a bit, but so slow that you can see the web page refreshing itself.

Recently, I came across a new project KaTeX. It’s fast as you can see the comparison below in which KaTeX is on the left and MathJax is on the right.

KaTeX vs Mathjax

So how to make KaTeX work in the Jekyll? Will Drevo offers a comprehensive manual to make it work. However, it requires us to write LaTeX code inside HTML div block. And I found this blog to explain how to use KaTeX with JavaScript. Combining both of these works, and with some extra effort, I find the approach to use KaTeX seamlessly inside Jekyll.

First of all, we need to configure Jekyll using Kramdown as markdown parser and MathJax as Kramdown’s math engine. In result, inline math equation will be rendered into a script block with “math/tex” as type. Like this: <script type="math/tex"> tex code </script>. Similarly the display style math equation will turn into a script block with “math/tex; mode=display” as type. Like this: <script type="math/tex; mode=display"> tex code </script>.

Secondly, let us put the required resources into the HTML head.

Finally, with the power of jQuery and KaTeX, we replace all the TeX code block to rendered high quality equations fast. But remember, this JavaScript should be loaded at the end of HTML file.

Here’s the final result of rendered equation in below. Also you can do whatever custom you want in CSS file using class inline-equation and equation.

P(x)=1σ2πe(xμ)22σ2 P(x)=\frac{1}{\sigma\sqrt{2\pi}}e^{-\frac{(x-\mu)^2}{2\sigma ^2}}