Search code examples
javascripthtmlmathjax

Can MathJax be imported to a JS file used by a local HTML document?


On the MathJax homepage, we find the code to import the tex-mml-chtml configuration directly into an HTML document, without any need for a server. Attempting to modify the example on jsbin below the boilerplate slightly, I separated the import statement into JS and HTML files on my local machine:

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>MathJax example</title>
  <script id="main"
          type="module"
          src="main.js">
  </script>
</head>

<body>
<p>
  When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) and they are
  \[x = {-b \pm \sqrt{b^2-4ac} \over 2a}.\]
</p>
</body>
</html>

main.js

import * as jax from "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js";

I get the following errors:

console errors

and a warped output, although it does still make an attempt:

warped output

I am not sure if this outcome is because we simply cannot use MathJax in this manner (the proper manner being a call in the source HTML document, or via a server), or rather because I am missing some JS, or because I am calling the wrong configuration, etc.

If this is not possible, an explanation of why not (perhaps some CORS machinery? using JS modules incorrectly? MathJax simply not designed that way?) would be appreciated!


Solution

  • MathJax sometimes needs to load additional resources that are not in the tex-mml-chtml file; in your case, it is the font files. So it needs to know where to get them. Normally, MathJax will look up the location where it was loaded using the src attribute of the script tag that loaded it. In your case, however, since you are importing it into another file instead of loading it with its own script tag, MathJax can't figure out where it should look for the other resources.

    In order to overcome that, you need to tell MathJax explicitly where you have placed its files. You can do that by including

    <script>
    window.MathJax = {
      loader: {
        paths: {
          mathjax: 'url-for-the-mathjax-files'
        }
      }
    };
    </script>
    

    before the script that loads MathJax itself (that is, before your main.js file is loaded). You can, of course, put the window.MathJax declaration into a separate file and import that into your main.js file before the import of tex-mml-chtml.js.

    As was mentioned in the comments, tex-mml-chtml.js does now have any exports, so you only need to do

    import "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js";
    

    to load it.