Last active
October 22, 2024 13:37
-
-
Save serg06/9b945e3f976f3f8efb5b01211936bfe9 to your computer and use it in GitHub Desktop.
[JS] Load scripts dynamically
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
// 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/[email protected]/dist/jszip.min.js', | |
'https://cdn.jsdelivr.net/npm/[email protected]/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
Here's an update where it supports attrs like
async
,defer
etc...