Created
May 6, 2017 20:11
-
-
Save JiLiZART/fefaf8a645b9d0d8ed423cca14530d38 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'); | |
}; | |
/** | |
* @exports | |
* @param {String} path resource link | |
* @param {Function} [success] to be called if the script succeeds | |
* @param {Function} [error] to be called if the script fails | |
*/ | |
module.exports = function (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 link = document.createElement('link'); | |
link.setAttribute('rel', 'stylesheet'); | |
link.setAttribute('type', 'text/css'); | |
link.setAttribute('href', (location.protocol === 'file:' && !path.indexOf('//') ? 'http:' : '') + path); | |
if ('onload' in link) { | |
link.onload = function () { | |
link.onload = link.onerror = null; | |
onSuccess(path); | |
}; | |
link.onerror = function () { | |
link.onload = link.onerror = null; | |
onError(path); | |
}; | |
} else { | |
link.onreadystatechange = function () { | |
var readyState = this.readyState; | |
if (readyState === 'loaded' || readyState === 'complete') { | |
link.onreadystatechange = null; | |
onSuccess(path); | |
} | |
}; | |
} | |
head.insertBefore(link, head.lastChild); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment