-
-
Save ademidoff/d68881050891ad854a640f6e8bb838b2 to your computer and use it in GitHub Desktop.
Dynamically load JavaScript files with callback when finished
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
// Examples: | |
JavaScript.load("/javascripts/something.js"); | |
JavaScript.load("http://www.someawesomedomain.com/api.js", function() { | |
API.use(); // or whatever api.js provides ... | |
}); | |
/** Tested with: | |
* - IE 5.5, 7.0, 8.0, 9.0 | |
* - Firefox 3.6.3, 3.6.8 | |
* - Safari 5.0 | |
* - Chrome 5.0 | |
* - Opera 10.10, 10.60 | |
*/ | |
var JavaScript = { | |
load: function(src, callback) { | |
var script = document.createElement('script'), | |
loaded; | |
script.setAttribute('src', src); | |
if (callback) { | |
script.onreadystatechange = script.onload = function() { | |
if (!loaded) { | |
callback(); | |
} | |
loaded = true; | |
}; | |
} | |
document.getElementsByTagName('body')[0].appendChild(script); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment