Search code examples
javascriptjqueryajaxmathjax

Unable to load MathJax dynamically


I have a ajax post request, which dynamically loads some math content like below

// post comment
    $post_comment.on("click", "[data-submit='post-comment']", function() {
        $.ajax({

            success: function(response) {
                if(response.success) {
                    $('#comment-list').load(' ' + '#comment-list');
                    MathJax.Hub.Queue(["Typeset",MathJax.Hub, "comment-list"]);

                }
            },

        });
   });

The mathjax command above mentioned is unable to render the math script loaded dynamically. While when I execute the same command on command-line, its working!!

It would be nice if someone explains why this is happening and how to fix


Solution

  • The load() method uses ajax which executes asynchronously meaning after the request is sent to the server the statements after that will continue executing without waiting for the response from server comes back.

    In this case when the load request is sent, before #comment-list is populated with the response the MathJax.Hub.Queue(["Typeset",MathJax.Hub, "comment-list"]); statement will get executed, thus it is not rendering anything.

    The solution is to use a callback provided by load to run the statements which has to work on elements loaded by the ajax request

    Ex

    $('#comment-list').load(' ' + '#comment-list', function(){
        MathJax.Hub.Queue(["Typeset",MathJax.Hub, "comment-list"]);
    });