Created
June 5, 2015 16:47
-
-
Save maxidr/83f0569d32dfd2a6acbf to your computer and use it in GitHub Desktop.
Load JS on demand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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