1. 新建loadScript.js

//动态加载外部js
//@param RESOURCE_LIST 外部地址集合["address"]
export function loadVoLteResourceList (RESOURCE_LIST,success) {
  return new Promise(r=>{
    RESOURCE_LIST.reduce((res, el) => res.then(() => loadScript(el)), Promise.resolve()).then(() => {
      r()
    }).catch((error) => {
      console.error('外呼VoLTE sdk 前置 js 资源加载失败:', error.name, error.message)
      return Promise.reject(error)
    })
  })
}

export function loadScript (url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')

    script.onload = () => resolve()

    script.onerror = () => reject(new Error(`Load script from ${url} failed`))

    script.src = url
    const head =
        document.head || document.getElementsByTagName('head')[0]
      ;(document.body || head).appendChild(script)
  })
}

2. 使用

import {loadVoLteResourceList} from "loadScript.js"
//可以传入多个地址
loadVoLteResourceList(["https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"])
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐