Created
December 19, 2018 12:37
-
-
Save leocristofani/576f9bd0eaa2acf022e4d43a35de8719 to your computer and use it in GitHub Desktop.
Micro-frontends in practice - load embed scripts from a micro-frontend
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
export function loadScript(url, name) { | |
let promise; | |
if (_scriptCache.has(url)) { | |
promise = _scriptCache.get(url); | |
} else { | |
promise = new Promise((resolve, reject) => { | |
let script = document.createElement('script'); | |
script.onerror = event => reject(new Error(`Failed to load '${url}'`)); | |
script.onload = resolve; | |
script.async = true; | |
script.src = url; | |
if (document.currentScript) { | |
document.currentScript.parentNode.insertBefore(script, document.currentScript); | |
} else { | |
(document.head || document.getElementsByTagName('head')[0]).appendChild(script); | |
} | |
}); | |
_scriptCache.set(url, promise); | |
} | |
return promise.then(() => { | |
if (global[name]) { | |
return global[name]; | |
} else { | |
throw new Error(`"${name}" was not created by "${url}"`); | |
} | |
}); | |
} | |
export function loadStyle(url) { | |
new Promise((resolve, reject) => { | |
let link = document.createElement('link'); | |
link.onerror = event => reject(new Error(`Failed to load '${url}'`)); | |
link.onload = resolve; | |
link.async = true; | |
link.href = url; | |
link.rel = 'stylesheet'; | |
(document.head || document.getElementsByTagName('head')[0]).appendChild(link) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment