Skip to content

Instantly share code, notes, and snippets.

@nasheomirro
Created March 10, 2024 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasheomirro/00781722da39e4ae549180ea17582d5e to your computer and use it in GitHub Desktop.
Save nasheomirro/00781722da39e4ae549180ea17582d5e to your computer and use it in GitHub Desktop.
makeshift dynamic import for non-module third party scripts
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();
});
}
// 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.
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