I have successfully loaded and configured MathJax by pasting MathJax recommended commands into the <head>
element of my webpage. MathJax does a great job rendering LaTex in the <body>
of my webpage.
My problem is with accessing the MathJax
object with javascript run at the very end of the <body>
element. For instance, the code below returns undefined
to the console. This is confusing to me- shouldn't my commands in the <head>
element have created MathJax
as a global variable that can be accessed anywhere?
Here's a screenshot of my code:
Here is the relevant section of code from the <head>
element:
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript" async
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML">
</script>
Here is the relevant section of code from the <body>
element:
<h1 class="header">
If $ax^2+bx+c=0$, then $x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}$.
</h1>
<script type="text/javascript" >
console.log(window.MathJax);
</script>
You are loading MathJax.js
with the async
attribute. Therefore, the browser does not block rendering until the script has loaded but instead continues to process the page. So now you have a race between MathJax.js
getting fetched and loaded vs the browser's parser getting to the script
tag further down in the page. Inevitably, the parser wins and executes the log before MathJax.js
has finished loading. Accordingly, there is no global MathJax
object.
If you remove async
, then the browser will first execute MathJax.js
before parsing the remaining page and thus the console.log
will provide something meaningful. (Similarly, on older browsers which do not support the async
attribute, you will get a result.)
Note, however, that MathJax is highly asynchronous in itself (loading additional components, configurations etc) so you will most likely need to synchronize your code with MathJax's APIs.