Last active
July 16, 2020 07:21
-
-
Save Dobby89/f9d12f2b257e447d068981cb9f21af27 to your computer and use it in GitHub Desktop.
DOM utils / helpers
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
export function injectScriptTag(src: string, id: string): Promise<boolean> { | |
// eslint-disable-next-line consistent-return | |
return new Promise((resolve, reject) => { | |
if (document.getElementById(id)) { | |
// Already exists | |
return resolve(true); | |
} | |
const allScripts = document.getElementsByTagName('script'); | |
const lastScriptTag = document.getElementsByTagName('script')[ | |
allScripts.length - 1 | |
]; | |
const scriptTag = document.createElement('script'); | |
scriptTag.id = id; // To avoid inserting the same thing more then once | |
scriptTag.onload = function () { | |
return resolve(true); | |
}; | |
scriptTag.onerror = (error) => { | |
return reject(error); | |
}; | |
scriptTag.src = src; | |
if (lastScriptTag && lastScriptTag.parentNode) { | |
lastScriptTag.parentNode.insertBefore( | |
scriptTag, | |
lastScriptTag.nextSibling | |
); | |
} | |
}); | |
} |
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
export function injectStyleTag(href: string, id: string): Promise<boolean> { | |
// eslint-disable-next-line consistent-return | |
return new Promise((resolve, reject) => { | |
if (document.getElementById(id)) { | |
// Already exists | |
return resolve(true); | |
} | |
const headEl = document.getElementsByTagName('head')[0]; | |
const linkTag = document.createElement('link'); | |
linkTag.id = id; // To avoid inserting the same thing more then once | |
linkTag.rel = 'stylesheet'; | |
linkTag.type = 'text/css'; | |
linkTag.onload = function () { | |
return resolve(true); | |
}; | |
linkTag.onerror = (error) => { | |
return reject(error); | |
}; | |
linkTag.href = href; | |
linkTag.media = 'all'; | |
headEl.appendChild(linkTag); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment