简体   繁体   中英

Import JavaScript file from within JavaScript synchronously?

Instead of messing up my HTML file, I'd like to import my external JavaScript files through another JavaScript file, much like @import in css.

On several websites, including StackOverflow itself, I noticed that appending a script tag to the DOM can solve this issue; however, this is done asynchronuosly, while the order of my files is important - the second file for example may rely on the first file in the list. When, say, loading jQuery first and then loading a dependency (plugin etc.) of it, the dependency might finish loading earlier and will throw errors because jQuery doesn't exist yet.

Therefore, this does not seem to be an option. How can I synchronously load JavaScript files from within another JavaScript file?

You cannot synchronously load JS files from within JS.

What you can do however, is implement a loader queue, something like this:

function ScriptLoader(queue) {
   this.started = false;
   this.queue = queue || [];
   this.currentIndex = 0;
   var self = this;
   this.next = function() {
     if(self.currentIndex == self.queue.length) return;
     self.load(self.queue[self.currentIndex]);
     self.currentIndex++;
   };
   this.load = function(dest) {
      var s = document.createElement('script');
      s.src = dest;
      document.getElementsByTagName('head')[0].appendChild(s);
      s.onload = self.next;
      if('onreadystatechange' in s) {
        s.onreadystatechange = function () {
          if (this.readyState == 'complete') {
             self.next();
          }
        }
      }
   };
}

ScriptLoader.prototype.start = function() {
    if(!this.started) {
       this.next();
       this.started = true;
    }
};


var loader = new ScriptLoader(['https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js', 'http://widgets.twimg.com/j/2/widget.js']);
loader.start();

In the above example, jQuery is loaded first, then jQuery UI , then the Twitter JS widget. :)

Look at RequireJS or LABjs for asynchronous loading of scripts. I would recommend using one of these libraries instead of rolling your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM