Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamically load JavaScript files with callback when finished
// Example:
JavaScript.load("/javascripts/something.js");
// 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);
}
};
@FLasH3r

This comment has been minimized.

Copy link

FLasH3r commented Aug 7, 2013

What about loading failure ? error handling ?

@PeterKnight

This comment has been minimized.

Copy link

PeterKnight commented Oct 30, 2013

looks like onreadystatechange is not future proof, won't be supported in IE 11+
http://msdn.microsoft.com/en-us/library/ie/ms536957(v=vs.85).aspx

@stiv-yakovenko

This comment has been minimized.

Copy link

stiv-yakovenko commented Apr 16, 2016

msdn says it will be replaced with script.onload, so it should work on IE.

@moltenform

This comment has been minimized.

Copy link

moltenform commented Feb 16, 2018

It looks like .onerror can be used to detect failures.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.