Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lucasconstantino/8324525 to your computer and use it in GitHub Desktop.
Save lucasconstantino/8324525 to your computer and use it in GitHub Desktop.
A simple function with no dependencies to load external javascripts. Features include:- Loading multiple scripts at once;- Callback function to execute once all scripts have loaded;- Optionally load scripts asynchronously;- Optionally define a DOM object where scripts will be inserted.
/**
* Snippet function to load external scripts.
* @param {[String, Array]} sources Array of sources to load.
* @param {[Functon]} callback A callback to run when all scripts have loaded.
* @param {[Boolean]} aasync Whether sources should be loaded
* asynchronously or not.
* @param {[Object]} appendTo Optionally provide a DOM object to append
* the script tags to.
*/
function scriptLoader(sources, callback, async, appendTo) {
// Parse variables.
sources = typeof sources == 'string' ? [sources] : sources || [];
async = typeof async == 'undefined' ? true : async;
appendTo = appendTo || document.body;
var toLoad = !async ? sources.splice(0, 1) : sources;
var scriptTag = null;
var i = l = 0; // Incrementals.
do {
// Terminate when iterator exceeds amount of items.
if (!toLoad[i]) return callback && callback(appendTo);
// Create script tag.
scriptTag = document.createElement('SCRIPT');
scriptTag.src = toLoad[i];
scriptTag.onload = function() {
var run = !async;
if (async && ++l == sources.length) {
run = true;
sources = [];
}
run && appendScripts(sources, callback, true, appendTo);
}
// Place script on document to load it.
appendTo.appendChild(scriptTag);
} while (++i < toLoad.length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment