在網頁、博客、React中配置mathjax

mathjax是一個非常好用的工具

在網頁端、博客上配置mathjax

  • 加載script
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  • 設置mathjax
<script> 
MathJax.Hub.Config({
    tex2jax: {
        skipTags: [
            'script', 
            'style', 
            'pre'
        ]
    }
}); 
</script>

react 加載mathjax, 下面是按需加載的mathjax

  • 加載marked
import marked from 'marked';
// ....
<div dangerouslySetInnerHTML={{__html: marked(this.props.content)}}></div>
  • 在文檔傳入後,判斷是否需要加載mathjax
componentWillReceiveProps = () => {
        // 如果原文包含 mathjax 表達式, 加載 mathjax組件
        if (this.props.content && this.props.content.indexOf('$$') !== -1) {
            let js_mathjax   = 'https://cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS_CHTML';
            this.loadJS(js_mathjax).then(function(msg){});
        }
    };

    componentWillMount = () => {
        if (this.props.content && this.props.content.indexOf('$$') !== -1) {
            let js_mathjax   = 'https://cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS_CHTML';
            this.loadJS(js_mathjax).then(function(msg){});
        }
    };
  • 動態加載JS方案
loadJS = (url) => {
        return new Promise(function(resolve, reject) {
            let script = document.createElement('script');
            script.type = "text/javascript";
            if (script.readyState){
                script.onreadystatechange = function() {
                    if (script.readyState === "loaded" ||
                        script.readyState === "complete") {
                        script.onreadystatechange = null;
                        resolve('success: '+url);
                    }
                };
            } else {
                script.onload = function(){
                    resolve('success: '+url);
                };
            }
            script.onerror = function() {
                reject(Error(url + 'load error!'));
            };
            script.src = url;
            document.body.appendChild(script);
        });
    };
  • 最後在markdown顯示的模塊下方加入
<div>
    Your Content
    {this.showMathJax}
</div>

// showMathjax:
showMathjax = () => {
        if (this.props.content && this.props.content.indexOf('$$') !== -1) {
            if(window.MathJax){
                window.MathJax.Hub.Queue(["Typeset",MathJax.Hub,"output"]);
            }else{
                setTimeout(this.runningMath.bind(this), 1000);
            }
        } else {
            return null;
        }
    };

runningMath = () => this.showMathjax()

mathjax 在網頁端公式顯示中是一個很好的解決方案。

$$mathjax: E=mc^2$$

效果:

mathjax:E=mc2

2018.7.13

最新建議使用 async await 方案實現。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章