Skip to content

Instantly share code, notes, and snippets.

@serg06
Last active July 2, 2023 01:13
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 serg06/9b945e3f976f3f8efb5b01211936bfe9 to your computer and use it in GitHub Desktop.
Save serg06/9b945e3f976f3f8efb5b01211936bfe9 to your computer and use it in GitHub Desktop.
[JS] Load scripts dynamically
// Function to load a JS file
async function loadScript(url) {
return await new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.addEventListener('load', () => resolve());
script.addEventListener('error', () => reject());
document.body.appendChild(script);
});
}
// Example: Loading 2 libraries
const scripts = [
'https://cdn.jsdelivr.net/npm/jszip@3.7.1/dist/jszip.min.js',
'https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js'
];
await Promise.all(scripts.map(url => loadScript(url)));
// 2023 UPDATE:
// If the library supports ESM, you can import it like this:
const {default: dayjs} = await import('https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js/+esm')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment