Skip to content

Instantly share code, notes, and snippets.

@JiLiZART
Created October 26, 2016 10:20
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 JiLiZART/4d75aa84579221a680ffc3854b28d558 to your computer and use it in GitHub Desktop.
Save JiLiZART/4d75aa84579221a680ffc3854b28d558 to your computer and use it in GitHub Desktop.
var loading = {},
loaded = {},
head = document.getElementsByTagName('head')[0],
runCallbacks = function(path, type) {
var cbs = loading[path], cb, i = 0;
delete loading[path];
while(cb = cbs[i++]) {
cb[type] && cb[type]();
}
},
onSuccess = function(path) {
loaded[path] = true;
runCallbacks(path, 'success');
},
onError = function(path) {
runCallbacks(path, 'error');
};
function loadJS(path, success, error) {
if(loaded[path]) {
success && success();
return;
}
if(loading[path]) {
loading[path].push({ success : success, error : error });
return;
}
loading[path] = [{ success : success, error : error }];
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.src = (location.protocol === 'file:' && !path.indexOf('//')? 'http:' : '') + path;
if('onload' in script) {
script.onload = function() {
script.onload = script.onerror = null;
onSuccess(path);
};
script.onerror = function() {
script.onload = script.onerror = null;
onError(path);
};
} else {
script.onreadystatechange = function() {
var readyState = this.readyState;
if(readyState === 'loaded' || readyState === 'complete') {
script.onreadystatechange = null;
onSuccess(path);
}
};
}
head.insertBefore(script, head.lastChild);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment