Skip to content

Instantly share code, notes, and snippets.

@ckimrie
Last active July 24, 2018 11:06
Show Gist options
  • Save ckimrie/5587857 to your computer and use it in GitHub Desktop.
Save ckimrie/5587857 to your computer and use it in GitHub Desktop.
Lightweight script loader with callback
/**
* Lightwright JS Loader
*
* @author Christopher Imrie
*
* @param {String} name URL to JS file
* @param {Function} cb Callback function
* @return {null}
*/
function loadScript(/** string */ name, /** Function*/ cb) {
var loaded = false,
url = String(name),
eed = document.createElement('script');
eed.type = 'text/javascript';
eed.async = true;
eed.src = url;
//Listen for script load
eed.onload = eed.onreadystatechange = function () {
if ((eed.readyState && eed.readyState !== "complete" && eed.readyState !== "loaded") || loaded) {
return false;
}
eed.onload = eed.onreadystatechange = null;
loaded = true;
//Fire callback on script load if supplied
if (typeof cb === "function") cb();
};
document.getElementsByTagName('head')[0].appendChild(eed);
}
/**
* Usage
*/
loadScript('http://path/to/file.js', function(){
//Code to run when JS has loaded
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment