Skip to content Skip to sidebar Skip to footer

Why Doesn't Browser Parse The Js Code In The File Loaded By Ajax?

I have 2 files, the first file has some HTML and a portion of JS. The second file is the main file, and it loads the first file thru' XmlHttpRequest. The first file is like this: &

Solution 1:

Ajax is asynchronous. Your code attempts to call my_function() before the XMLHttpRequest has completed. Do this instead:

<script>functionload_ajax_content() {
    //...load and throw the first file into 'div_ajax_content'// then,my_function();
}

load_ajax_content();
</script>

Okay, so now your ajax call is synchronous. You can parse the returned HTML for <script> tags, and handle them separately, but it's not pretty:

functionload_ajax_content() {
    //...load and throw the first file into 'div_ajax_content'// then grab the script nodes one-by-onevar scriptElts = document.getElementById('div_ajax_content').getElementsByTagName('script'),
        scriptElt,
        propName; // http://www.quirksmode.org/dom/w3c_html.html#t07if (scriptElts.length) {
        propName = scriptElts[0].textContent ? 'textContent' : 'innerText';
    }

    for (var i=0; i<scriptElts.length; i++) {
        scriptElt = document.createElement('script');
        scriptElt[propName] = scriptElts[i][propName];
        document.body.appendChild(scriptElt);
    }

    // finally,my_function();
}

...or you could just use a library like jQuery, which automagically handles this exact problem (and many others!) for you.

Solution 2:

Adding a script via innerHTML does NOT run the script. Therefore your function is not being defined, hence the failure.

Instead, I suggest loading HTML and JS separately, and either appending the JS using DOM methods to put the <script> tag on the page, or eval() to execute the returned file contents.

Solution 3:

Following Kolink I found a pretty funny method but it works!

load_ajax_contents();
eval(document.getElementById("my_js_block").innerHTML);
my_function();

However, in order to make those functions evaluated by 'eval()' global, all the functions in the first file must be declared as variables, like this:

//this works!
my_function = function() {
  alert(9);
}

and not:

//this makes the function nested in the context where eval() is called
function my_function() { 
  alert(9);
}

and also not:

//this makes the variable local to the context where eval() is calledvar my_function = function() {
  alert(9);
}

Post a Comment for "Why Doesn't Browser Parse The Js Code In The File Loaded By Ajax?"