Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import JavaScript file from within JavaScript synchronously?

Tags:

javascript

dom

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?

like image 671
pimvdb Avatar asked May 19 '26 16:05

pimvdb


2 Answers

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. :)

like image 53
Jacob Relkin Avatar answered May 21 '26 08:05

Jacob Relkin


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

like image 36
Ates Goral Avatar answered May 21 '26 08:05

Ates Goral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!