If you need a way to load external JavaScript files sequentially with JavaScript, you can use the following function:

/**
 * Loads one more external JS files and optionally calls a callback function
 * when done.
 * @param {!Array.<string>} urls
 *     URLs of external JS files to load.
 * @param {function(!Array.<!Object>)|udefined} callback
 *     Optional callback function to execute once all of the scripts have been
 *     loaded.  The parameter passed will be an array of objects containing the
 *     "script", "url", and "event" (event name fired indicating the script
 *     loaded).
 */
var loadSequentialJS = (function(document) {
  return function(urls, callback) {
    var results = [];
    var parent = document.getElementsByTagName('head')[0] || document.body;
    var urlsLeft = urls.length;
    
    function loadNext(len, script, url, eventName) {
      if (urlsLeft == len) {
        if (eventName) {
          results.push({
            script: script,
            url: url,
            event: eventName
          });
        }
        if (urlsLeft) {
          var url = urls.shift();
          len = --urlsLeft;
          var script = document.createElement('script');
          script.src = url;
          script.onload = function() {
            loadNext(len, script, url, 'load');
          };
          script.onerror = function() {
            loadNext(len, script, url, 'error');
          };
          parent.appendChild(script);
        }
        else if (callback) {
          callback(results);
        }
      }
    }
    loadNext(urlsLeft);
  };
})(document);

If you want to load two scripts up you could do it as follows:


// Load http://example.com/script1.js and http://example.com/script2.js
// on any page under the http://example.com/ domain.
loadSequentialJS(['http://example.com/script1.js', '/script2.js']);

Here is the Closure Compiler version of the above function if you want to use it. šŸ˜Ž

Categories: BlogJavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *