Skip to content

Instantly share code, notes, and snippets.

@CongAn
Last active April 27, 2022 09:57
Show Gist options
  • Save CongAn/afaada9320e9f9dadbd0130ea66d6d3d to your computer and use it in GitHub Desktop.
Save CongAn/afaada9320e9f9dadbd0130ea66d6d3d to your computer and use it in GitHub Desktop.
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/moment@2.29.1/min/moment.min.js')
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment