-->

load Mathjax after loading javascript

2020-07-27 04:40发布

问题:

here is my simple HTML code

<html>
<head>
<script type="text/javascript"
 src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
</script>
</head>
<body>
<p>This is the line that load correct  \[ \frac{x+y}{z} \]</p>
<p id="step1"></p>
<script>
var x = gup('x');
var y = gup('y');
var z = gup('z');
var text = "This is the line that NOT show correct" + "\[ \frac{" + x + " + " + y + "}{" + z +"}\]";
document.getElementById("step1").innerHTML= text;
</script>
</body>
</html>

when I load this html file and send parameters by url like

sample.html?x=1&y=2&z=3

the first sentence shows correct form and load Mathjax but the second sentence NOT. it is because Mathjax load before the java script code. do you know how to load Mathjax after Javascript?

回答1:

You can try using a JavaScript loader with a callback to load MathJax and run your code in the callback. See https://github.com/niftylettuce/javascript-async-callback for example.

EDIT:

<html>
<head>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
</script>

<script>
$(function() {
  var x = gup('x');
  var y = gup('y');
  var z = gup('z');
  var text = "This is the line that NOT show correct <-- It's OK now" + "\\[ \\frac{" + x + " + " + y + "}{" + z +"} \\]";
  document.getElementById("step1").innerHTML= text;
});
</script

</head>
<body>
<p>This is the line that load correct  \[ \frac{x+y}{z} \]</p>
<p id="step1"></p>
</body>
</html>


回答2:

If you modify the document to add mathematics after MathJax has run, you need to tell MathJax to run again. You do that using

<script>
  MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
</script>

See the relvent MathJax documentation for details.

In your case, this should do it:

<script>
var x = gup('x');
var y = gup('y');
var z = gup('z');
var text = "This is the line that NOT show correct" + "\[ \frac{" + x + " + " + y + "}{" + z +"}\]";
document.getElementById("step1").innerHTML= text;
MathJax.Hub.Queue(["Typeset",MathJax.Hub,"step1"]);
</script>