Skip to content Skip to sidebar Skip to footer

How Can I Control Javascript Execution Order?

I'm having some concurrency issues with a webpage I'm building. Basically, I have three script files that I'm using to hold some data: script1.js: var myValue = 1; script2.js: var

Solution 1:

This method of dynamically loading script files using DOM methods like head.appendChild is asynchronous, meaning that the page does not wait for it to load before running any further code. If you did not want this asynchronous behaviour, you could load them with regular elements in your HTML, or you could mess around with a 'synchronous' XMLHttpRequest to grab it and eval() to run it.

You probably don't want to do that, though, because being asynchronous makes the entire page load faster, anyway. You will probably just need to add some logic that waits for the dynamically loaded script to have loaded before you go on with the next bit of code. This may, however, involve polling using setInterval() until you notice a variable from the included script has been defined. Or, you could add code in the included script that calls a method to whatever has been waiting for it.

Or, you could look at how jQuery does something similar, look for where the ajax method is defined, specifically these parts...

var script = document.createElement("script");

// then later ...

script.onload = script.onreadystatechange = function(){
    if ( !done && (!this.readyState ||
    this.readyState == "loaded" || this.readyState == "complete") ) {

        // do processing
            head.removeChild( script );
    }
};

// ...

head.appendChild(script);

Solution 2:

Could you possibly add a function call to your script files, so that when they're run, they call the function that does your

document.write( myValue );

So that script1.js would be

var myValue = 1;
scriptLoaded();

and your main file would have:

functionscriptLoaded(){
   document.write( myValue );
}

Post a Comment for "How Can I Control Javascript Execution Order?"