Created
July 15, 2018 11:09
-
-
Save frankinedinburgh/f24a02009a1db3c367b2950b2c8d7cff to your computer and use it in GitHub Desktop.
dynamically load a script
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
const loadScript = (() => { | |
const _loadedScripts = {}; | |
return (src) => { | |
if (_loadedScripts[src]) { | |
return _loadedScripts[src]; | |
} | |
return ( // eslint-disable-line no-return-assign | |
_loadedScripts[src] = new Promise(_injectScriptTag) | |
); | |
function _injectScriptTag(resolve, reject) { | |
const element = document.createElement('script'); | |
const target = document.getElementsByTagName('script')[0]; | |
element.src = src; | |
element.async = 1; | |
element.onload = resolve; | |
element.onerror = reject; | |
target.parentNode.insertBefore(element, target); | |
} | |
}; | |
})(); | |
export default loadScript; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment