How can I control Javascript execution order?

24

Solution 1

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:

function scriptLoaded(){
   document.write( myValue );
}

Solution 2

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);
Share:
24
Bloch Sphere
Author by

Bloch Sphere

Updated on June 04, 2022

Comments

  • Bloch Sphere
    Bloch Sphere almost 2 years

    A commenter in the post How to get a node with index n in Lemon Graph Library? states that LEMON's nodeFromId() function is linear in time complexity.

    However, in the developers' paper LEMON – an Open Source C++ Graph Template Library they say

    The general graph types of LEMON store the adjacency lists internally in std::vectors and use the vector indices as identifiers of the nodes and arcs. Node and Arc objects store these indices, thus for each of them, the corresponding vector element can be looked up in constant time.

    Please confirm either of these contradictory statements or explain my misconceptions.