Last active
July 2, 2023 01:13
-
-
Save serg06/9b945e3f976f3f8efb5b01211936bfe9 to your computer and use it in GitHub Desktop.
[JS] Load scripts dynamically
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
// 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