python-sphinxmathjax

How to include MathJax in local Sphinx build without CDN?


I'm trying to include MathJax in my local _static Sphinx directory to avoid the overhead of downloading it on rebuilds while developing locally. I followed the instructions and set mathjax_path in conf.py as shown below, having copied tex-mml-chtml.js to docs/_static/MathJax/tex-mml-chtml.js as said in the Sphinx docs:

html_static_path = ["_static"]
mathjax_path = "MathJax/tex-mml-chtml.js"
mathjax3_config = {
    'loader': {'load': ['[tex]/mathtools']},
    'tex': {'packages': {'[+]': ['mathtools']}}
}

The usual make html build works if I do not set mathjax_path and let Sphinx use its defaults (downloading MathJax from a CDN). So using this example:

.. math::
    \begin{array}{l}
    f = \underbrace{x^3}_\textrm{text 1} + \underbrace{2}_\textrm{text 2}
    \end{array}

with the commented line in conf.py:

# mathjax_path = "MathJax/tex-mml-chtml.js"
mathjax3_config = {
    'loader': {'load': ['[tex]/mathtools']},
    'tex': {'packages': {'[+]': ['mathtools']}}
}

Gives the expected result:

an equation example

And if I don't specify mathjax_path this is included in the HTML and it works:

<script>window.MathJax = {"loader": {"load": ["[tex]/mathtools"]}, "tex": {"packages": {"[+]": ["mathtools"]}}}</script>
<script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>


But if I uncomment # mathjax_path = "MathJax/tex-mml-chtml.js" MathJax doesn't work anymore, just giving the broken content of the :math: directive without rendering it:

broken rendering of the equation

this is included in the HTML:

<script>window.MathJax = {"loader": {"load": ["[tex]/mathtools"]}, "tex": {"packages": {"[+]": ["mathtools"]}}}</script>
<script defer="defer" src="_static/MathJax/tex-mml-chtml.js?v=cadf963e"></script>

What am I doing wrong? I compared the hash of the CDN distribution and my local file and they're the same. Should I have included a different file other than tex-mml-chtml.js? Should I have included more files like loader.js from MathJax? Because looking at the Sphinx docs it seems the paths are alright, I checked the build and the file is there in _static... I also searched for reported bugs for this functionality in the Sphinx repository but it seems there are none.


Solution

  • After checking the Firefox console for JS errors I noticed MathJax wasn't able to load some components locally. To get it to work locally with Sphinx I downloaded the whole MathJax library from GitHub via browser (there are other ways to get MathJax) and pointed mathjax_path to the specific script that MathJax chooses, in my use case (see the source HTML snippets in the question), when running from CDN namely es5/tex-mml-chtml.js.

    Using an absolute path it's worth showing the syntax that worked for me on Windows in conf.py:

    mathjax_path = "file:///C:/MathJax-master/es5/tex-mml-chtml.js"