MathJax-demos-web

load-mathjax.html

This example shows how to load MathJax only when there is actual math in the page, and no load MathJax otherwise. This could be used, for example, in the common header for a collection of pages, say ones that are generated by a wiki or blog system. That way, pages without math will not require the download of MathJax’s code and font information.

This uses a script file load-mathjax.js containing the following:

(function () {
  if (document.body.querySelector('math') ||
      document.body.textContent.match(/(?:\$|\\\(|\\\[|\\begin\{.*?})/)) {
    if (!window.MathJax) {
      window.MathJax = {
        tex: {
          inlineMath: {'[+]': [['$', '$']]}
        }
      };
    }
    var script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    document.head.appendChild(script);
  }
})();

This checks the page for either the presence of <math> elements, or for the various standard TeX math delimiters ($, $$, \(, \[, or \begin{...}), and only loads MathJax if one is present. If so, it sets up the MathJax global variable (if one isn’t present) in order to include the single-dollar delimiters, and then loads the tex-mml-chtml combined component file to process both MathML and TeX.

If you want only MathML or only TeX, you can modify the script accordingly. If you use different delimiters for TeX, modify the regular expression to use your delimiters.

In your web page, you need only include

  <script src="load-mathjax.js" id="MathJax-script" async></script>

to load and run this small script file. Adjust the src attribute to include the path to load-mathjax.js if it is not in the same directory as the HTML file itself.

Run the example