Skip to content

Instantly share code, notes, and snippets.

@maxidr
Created June 5, 2015 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxidr/83f0569d32dfd2a6acbf to your computer and use it in GitHub Desktop.
Save maxidr/83f0569d32dfd2a6acbf to your computer and use it in GitHub Desktop.
Load JS on demand
// Inspired (stolen?) from JQuery (https://github.com/jquery/jquery/blob/1.3.2/src/ajax.js#L264)
// and http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/
function loadJS(url, callback){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
script.async = true;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !this.readyState || this.readyState == "loaded" || this.readyState == "complete" ) {
callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment