Created
December 18, 2017 19:18
-
-
Save gabemeola/0d4ef446133b1bc7f6a854d0ef9f5be7 to your computer and use it in GitHub Desktop.
Helper function for inserting external script tags
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
/** | |
* Inserts a script tag of src | |
* in the Head of HTML. | |
* | |
* @param {string} src - Src for Javascript request | |
* @param {Object} config | |
* @return {Promise} - Returns a promise of event when loaded / error | |
*/ | |
export default function insertScript(src, { async = true, defer = false } = {}) { | |
return new Promise((resolve, reject) => { | |
const gptScript = document.createElement('script'); | |
gptScript.async = async; | |
gptScript.defer = defer; | |
gptScript.type = 'text/javascript'; | |
gptScript.src = src; | |
gptScript.onload = resolve; | |
gptScript.onerror = reject; | |
// Fetch! | |
document | |
.getElementsByTagName('head')[0] | |
.appendChild(gptScript); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment