Dynamically Load Javascript Files Using XHR

It probably won’t be often, but sometimes you may find yourself having the need to load Javascript dynamically using XHR.

 

To name a few use cases:

  • Developing a plugin architecture for an HTML5 application.
  • In order to extend your application’s functionality.
  • Load certain Javascript depending the browser environment.

A demo can be found here and the source here.

This method of loading an external Javascript file simply appends a dynamically generated script tag into the head of the HTML document. Note that this only loads the Javascript file; if you’re creating a plugin architecture, you’ll probably need to unload it somehow (you’ll likely want to implement an unload method within the Javascript object you loaded).

Implementation is easy, just specify a Javascript file to load using the load method of the fetchJs object:

var js = new fetchJs();
js.load('a.js');

If you want to issue a callback, you can use the following syntax:

var js = new fetchJs();
js.load({
  url: 'a.js',
  callback: function () { console.log('a.js loaded!'); }
});

Want to load consecutive scripts?

var js = new fetchJs();
js.load({
  url: 'a.js',
  callback: function () {
    js.load({
      url: 'a_nutter.js',
      callback: function () {
        console.log('a_nutter.js successfully loaded!');
      }
    });
    console.log('a.js successfully loaded!');
  }
});

Just remember that the innermost Javascript will load last (something to keep in mind especially if you have scripts dependent on one another).

NOTE: You won’t be able to fetch a Javascript file across different domains or protocol (i.e. HTTP/HTTPS). The safest way to do this is via CORS, which requires you have access to the hosting server.