Chainloading JS libraries on the fly

Loading Javascript libraries with <script src=””> lines is easy. But there are instances when you need to load JS libraries but you can’t use that. One example is loading HTML into a <div> via JS. Any <script src=””> lines are just ignored. That’s way you want to be able to load JS libraries on the fly. To do this, you have to work asynchronously and keep in mind that you need to load them sequentially since a library might have dependencies on the previously library.

To do this cleanly we can call loadScript () at any time. This function will load all the libraries given and then call a user defined function when it’s done. In my case I wanted to draw a chart with the HighCharts libraries in a <div> that I loaded when the user clicked a button:

function loadScript(urls, callback, value)
{
if(!Array.isArray(urls))                             // Allow a single URL or an array of multiple URLs
  urls = [ urls ];

if(urls.length == 0)                                 // The chain is loaded, do the user defined callback
  {
  callback(value);
  return;
  }

var url     = urls.shift();
var head    = document.getElementsByTagName('head')[0];
var s       = document.createElement('script');
s.type      = 'text/javascript';
s.src       = url;
s.urls      = urls;                                  // Save these to pass along
s.cCallback = callback;
s.cValue    = value;
s.onload    = loadScriptChain;                       // Set the chainloader for the next script

head.appendChild(s);                                 // Load the current script
}

function loadScriptChain()                           // This is the callback to load the next script in the chain
{loadScript(this.urls, this.cCallback, this.cValue);}

function doChart(x)
{
console.log("I've been called with: " + x);
// At this point I can call draw a chart since all the code has been loaded
}

loadScript(["https://code.highcharts.com/highcharts.js",
            "https://code.highcharts.com/modules/series-label.js"],
            doChart,
            "Hi there");

Leave a Comment

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