How can I delay JS code execution until ALL my asynchronous JS files load?

UPDATE

I have the following code:

<script type="text/javascript">
function addScript(url) {
    var script = document.createElement('script');
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
}   
addScript('http://google.com/google-maps.js');
addScript('http://jquery.com/jquery.js');

...

// run code below this point once both google-maps.js & jquery.js has been downloaded and excuted

</script>

How can I prevent code from being executed until all necessary JS are loaded and executed? In my example above, these required files were google-maps.js and jquery.js.

+5
source share
2 answers

You can use the onloadscript element event for most browsers and use the callback argument:

Edit: You really cannot stop code execution when loading scripts this way (and synchronous Ajax requests are a bad idea in most cases).

, , , : Two.js Three.js, , :

loadScript('http://example.com/Two.js', function () {
  // Two.js is already loaded here, get Three.js...
  loadScript('http://example.com/Three.js', function () {
    // Both, Two.js and Three.js loaded...
    // you can place dependent code here...
  });
});

:

function loadScript(url, callback) {
  var head = document.getElementsByTagName("head")[0],
      script = document.createElement("script"),
      done = false;

  script.src = url;

  // Attach event handlers for all browsers
  script.onload = script.onreadystatechange = function(){
    if ( !done && (!this.readyState || // IE stuff...
      this.readyState == "loaded" || this.readyState == "complete") ) {
      done = true;
      callback(); // execute callback function

      // Prevent memory leaks in IE
      script.onload = script.onreadystatechange = null;
      head.removeChild( script );
    }
  };
  head.appendChild(script);
}

IE onreadystatechange.

+6

CMS , " " , , . .

, , .

var poll = window.setInterval(function() {

    if (typeof myVar !== 'undefined') {
        clearInterval(poll);
        doSomething();
    };

}, 100);
0

All Articles