Skip to content

Instantly share code, notes, and snippets.

@IAMtheIAM
Forked from hagenburger/javascript_loader.js
Last active January 12, 2017 18:10
Show Gist options
  • Save IAMtheIAM/2355d8a7aea29751abd67004618e2e7d to your computer and use it in GitHub Desktop.
Save IAMtheIAM/2355d8a7aea29751abd67004618e2e7d to your computer and use it in GitHub Desktop.
Dynamically load JavaScript files with callback when finished
// Example:
function myCallback() {
// cool stuff here
}
// don't invoke the function here with () i.e. myCallback(), just reference the name of it it - myCallback.
JavaScript.load("/javascripts/something.js", myCallback);
// With callback (that’s the good thing):
JavaScript.load("http://www.someawesomedomain.com/api.js", function() {
API.use(); // or whatever api.js provides ...
});
/** Testet with:
* - IE 5.5, 7.0, 8.0, 9.0 (preview)
* - 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('head')[0].appendChild(script);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment