How can I control Javascript execution order?

后端 未结 2 1650
甜味超标
甜味超标 2020-12-12 00:53

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:

2条回答
  •  攒了一身酷
    2020-12-12 01:43

    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);
    

提交回复
热议问题