Last active
May 31, 2016 11:52
-
-
Save radist2s/7799639 to your computer and use it in GitHub Desktop.
JS Script loader
This file contains 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
/** | |
* Usage: | |
* loadScript('//exmp.com/script.js') | |
* loadScript('//exmp.com/script-another.js', function(){runCallback()}, {'data-attribute': 'has'}) | |
* Will not be loaded, because loaded earlier: | |
* loadScript('//exmp.com/script.js') | |
**/ | |
/** @type {loadScript} */ | |
var loadScript = (function () { | |
var loadedScripts = {}, | |
jsQueryRegex = /\?[\S\s]+$/ | |
/** | |
* @name loadScript | |
* @param {string} src | |
* @param {function} [callback] | |
* @param {object} [attributes] | |
*/ | |
function loadScript(src, callback, attributes) { | |
if (typeof callback != 'function') { | |
callback = function () {} | |
} | |
var jsName = src.replace(jsQueryRegex, '') | |
if (loadedScripts[jsName] === true) { | |
return callback() | |
} | |
else { | |
loadedScripts[jsName] = loadedScripts[jsName] || [] | |
loadedScripts[jsName].push(callback) | |
} | |
var script = document.createElement('script') | |
if (attributes && attributes instanceof Object) { | |
for (var key in attributes) { | |
if (attributes.hasOwnProperty(key)) { | |
script.setAttribute(key, attributes[key]) | |
} | |
} | |
} | |
script.onload = script.onreadystatechange = function() { | |
if (this.readyState && !(this.readyState === 'loaded' || this.readyState === 'complete')) { | |
return | |
} | |
var scriptCallbacks = loadedScripts[jsName] | |
for (var callback in scriptCallbacks) { | |
if (scriptCallbacks.hasOwnProperty(callback)) { | |
scriptCallbacks[callback]() | |
delete scriptCallbacks[callback] | |
} | |
} | |
loadedScripts[jsName] = true | |
delete script.onreadystatechange | |
delete script.onload | |
} | |
script.type = 'text/javascript' | |
script.src = src | |
document.head.appendChild(script) | |
} | |
return loadScript | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment