Loading MathJax Only When Needed

This page demonstrates a technique for loading MathJax in pages only when they contain mathematical notation, and not otherwise. Use the "Show Source' button below to see the details.

This is math in TeX: $$x+1\over x-1$$

This is MathML: 1 - x 2

This example shows how to load MathJax only when there is actual math in the page, and not 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:

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

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.

The key sections of the HTML for this page are shown below: