加载JavaScript后加载Mathjax

时间:2012-09-27 12:33:22

标签: javascript html mathjax

这是我简单的HTML代码

<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>

当我加载这个html文件并通过url发送参数时,如

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

第一句显示正确的形式和加载Mathjax,但第二句不是。这是因为Mathjax在java脚本代码之前加载。你知道如何在Mathjax之后加载Javascript吗?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用带有回调的JavaScript加载程序来加载MathJax并在回调中运行您的代码。 例如,请参阅https://github.com/niftylettuce/javascript-async-callback

编辑:

<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>

答案 1 :(得分:2)

如果在MathJax运行后修改文档以添加数学,则需要告诉MathJax再次运行。你这样做是用

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

有关详细信息,请参阅relvent MathJax documentation

在你的情况下,这应该这样做:

<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>