How to compile Javascript loaded by Ajax?

Discussion in 'Articles & Tutorials' started by Kristine, Aug 15, 2012.

  1. Kristine

    Kristine
    uix_expand uix_collapse
    New Member

    Joined:
    Jun 20, 2012
    Messages:
    25
    Likes Received:
    1
    As default, the browser doesn’t compile the script responded by Ajax. If you use the function eval() to compile your script, the variable (defined in your Ajax response code) will be unavailable to call in your page. Thus I have a tip that may help you solve this issue. You can call the function below to compile your script loaded by Ajax.
    // Compile your custom script
    function compileJsAjax(yourScript){
    var jsElement = document.createElement('script');
    jsElement.type = 'text/javascript';
    jsElement.text = yourScript;
    var existedJs = document.getElementsByTagName('script')[0];
    existedJs.parentNode.insertBefore(jsElement,existedJs);
    }
    For example:
    new Ajax.Request(requestUrl,{
    method: 'post',
    postBody: '',
    parameters: '',
    onComplete: function(xhr){
    var response = xhr.responseText;
    var scripts = response.extractScripts();
    for (var i=0;i********s.length;i++)
    compileJsAjax(scripts);
    }
    });
    If your response is a Javascript source (such as: http://yourstore.com/test.js), you can modify the function to get and compile this source.
    // Load and compile your script source
    function ajaxLoadJs(jsSource){
    var jsElement = document.createElement('script');
    jsElement.type = 'text/javascript';
    jsElement.async = true;
    jsElement.src = jsSource;
    var existedJs = document.getElementsByTagName('script')[0];
    existedJs.parentNode.insertBefore(jsElement,existedJs);
    }
    I hope this helps. Thanks for reading!
     

Share This Page