How can I get make JavaScript code execution to wait until an AJAX request with script is loaded and executed?

Posted by Edward Tanguay on Stack Overflow See other posts from Stack Overflow or by Edward Tanguay
Published on 2011-03-18T16:01:54Z Indexed on 2011/03/18 16:09 UTC
Read the original article Hit count: 439

Filed under:
|
|
|

In my application, I am using Ext.Ajax.request to load scripts which I execute with eval.

The problem is that since it takes time for the AJAX request to complete, code that is executed afterward which needs variables which are in the script loaded in via AJAX. In this example, I show how this is the case. How can I change this code so that the execution of the JavaScript after the AJAX waits until the script in the AJAX call has been loaded and executed?

testEvalIssue_script.htm:

<script type="text/javascript">
    console.log('2. inside the ajax-loaded script');
</script>

main.htm:

<html>
    <head>
        <script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script>
        <script type="text/javascript" src="ext/ext-all-debug.js"></script>
        <script type="text/javascript">
            function loadViewViaAjax(url) {
                Ext.Ajax.request({
                    url: url,
                    success: function(objServerResponse) {
                        var responseText = objServerResponse.responseText;
                        var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
                        while(scripts=scriptsFinder.exec(responseText)) {
                            eval.call(window,scripts[1]);
                        }
                    }
                });
            }

            console.log('1. before loading ajax script');
            loadViewViaAjax('testEvalIssue_script.htm');
            console.log('3. after loading ajax script');
        </script>
    </head>
    <body>

    </body>

</html>

output:

1. before loading ajax script
3. after loading ajax script
2. inside the ajax-loaded script

How can I get the output to be in the correct order, like this:

1. before loading ajax script
2. inside the ajax-loaded script
3. after loading ajax script

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about AJAX