Last active
April 27, 2022 09:57
-
-
Save CongAn/afaada9320e9f9dadbd0130ea66d6d3d to your computer and use it in GitHub Desktop.
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 loadScript (FILE_URL, async = true, type = 'text/javascript') { | |
return new Promise((resolve, reject) => { | |
try { | |
const scriptEle = document.createElement('script') | |
scriptEle.type = type | |
scriptEle.async = async | |
scriptEle.src = FILE_URL | |
scriptEle.addEventListener('load', (ev) => { | |
resolve() | |
}) | |
scriptEle.addEventListener('error', (ev) => { | |
reject(new Error(`Failed to load the script ${FILE_URL}`)) | |
}) | |
document.body.appendChild(scriptEle) | |
} catch (error) { | |
reject(error) | |
} | |
}) | |
} | |
// 例子:动态加载moment库 | |
;(async () => { | |
await loadScript('https://unpkg.com/[email protected]/min/moment.min.js') | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment