Created
October 26, 2016 10:20
-
-
Save JiLiZART/4d75aa84579221a680ffc3854b28d558 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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