Blame view

yudao-ui-admin/src/utils/loadScript.js 1.52 KB
0773a4c4   YunaiV   多模块重构 12:修改项目名字,按...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  const callbacks = {}
  
  /**
   * 加载一个远程脚本
   * @param {String} src 一个远程脚本
   * @param {Function} callback 回调
   */
  function loadScript(src, callback) {
    const existingScript = document.getElementById(src)
    const cb = callback || (() => {})
    if (!existingScript) {
      callbacks[src] = []
      const $script = document.createElement('script')
      $script.src = src
      $script.id = src
      $script.async = 1
      document.body.appendChild($script)
      const onEnd = 'onload' in $script ? stdOnEnd.bind($script) : ieOnEnd.bind($script)
      onEnd($script)
    }
  
    callbacks[src].push(cb)
  
    function stdOnEnd(script) {
      script.onload = () => {
        this.onerror = this.onload = null
        callbacks[src].forEach(item => {
          item(null, script)
        })
        delete callbacks[src]
      }
      script.onerror = () => {
        this.onerror = this.onload = null
        cb(new Error(`Failed to load ${src}`), script)
      }
    }
  
    function ieOnEnd(script) {
      script.onreadystatechange = () => {
        if (this.readyState !== 'complete' && this.readyState !== 'loaded') return
        this.onreadystatechange = null
        callbacks[src].forEach(item => {
          item(null, script)
        })
        delete callbacks[src]
      }
    }
  }
  
  /**
   * 顺序加载一组远程脚本
   * @param {Array} list 一组远程脚本
   * @param {Function} cb 回调
   */
  export function loadScriptQueue(list, cb) {
    const first = list.shift()
    list.length ? loadScript(first, () => loadScriptQueue(list, cb)) : loadScript(first, cb)
  }
  
  export default loadScript