Import javascript file from javascript synchronously?

Instead of messing up my HTML file, I would like to import external JavaScript files through another JavaScript file, like @importin css.

On several sites, including StackOverflow itself, I noticed that adding a script tag to the DOM can solve this problem; however, this is done asynchronously, while the order of my files is important - the second file, for example, can rely on the first file in the list. When, say, jQuery first loads and then a dependency is loaded (plugin, etc.), the Dependency may finish loading earlier and will cause errors because jQuery does not exist yet.

Therefore, this does not seem like a choice. How can I synchronously load javascript files from another javascript file?

+3
source share
2 answers

You cannot synchronously download JS files from JS.

However, you can execute the implementation queue, for example:

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, it loads first jQuery, then jQuery UI, then the Twitter JS widget. :)

+7
source

See RequireJS or LABjs for asynchronous script loading. I would recommend using one of these libraries instead of riding on your own.

+3
source

Source: https://habr.com/ru/post/1788589/


All Articles