Created
March 10, 2024 19:15
-
-
Save nasheomirro/00781722da39e4ae549180ea17582d5e to your computer and use it in GitHub Desktop.
makeshift dynamic import for non-module third party scripts
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
async function importScript(src: string) { | |
const script = document.createElement('script'); | |
script.src = src; | |
document.body.appendChild(script); | |
return new Promise((res, rej) => { | |
script.onload = () => res(); | |
}); | |
} |
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
// if you want to load the script multiple times, you have to make a way for | |
// it to remember that it already ran that script, the simplest is to have a list of | |
// all the src keys. | |
// for initial third-party scripts attached, this code assumes it is ran after the DOM has loaded | |
const srcKeys = document.querySelectorAll('script[data-third-party]'); | |
async function importScript(src: string) { | |
if (srcKeys.includes(src)) return; | |
const script = document.createElement('script'); | |
script.src = src; | |
document.body.appendChild(script); | |
await (new Promise((res, rej) => { | |
script.onload = () => res(); | |
})); | |
srcKeys.push(src); | |
} | |
// of course, you can get fancier with this, maybe you want a more general check where the origin is enough, or a specific src path. |
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
import { importScript } from "./importScript.ts"; | |
document.querySelector('#trigger-btn').addEventListener('hover', async () => { | |
await importScript('third-party.com/do-something'); | |
// afterwards, any global variables and what not would be available: | |
window.ThirdPartyGlobal.widget(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment