动态脚本加载

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
export default function remoteLoad (url, hasCallback) {
return createScript(url)
/**
* 创建script
* @param url
* @returns {Promise}
*/
function createScript (url) {
var scriptElement = document.createElement('script')
document.body.appendChild(scriptElement)
var promise = new Promise((resolve, reject) => {
scriptElement.addEventListener('load', e => {
removeScript(scriptElement)
if (!hasCallback) {
resolve(e)
}
}, false)

scriptElement.addEventListener('error', e => {
removeScript(scriptElement)
reject(e)
}, false)

if (hasCallback) {
window.____callback____ = function () {
resolve()
window.____callback____ = null
}
}
})

if (hasCallback) {
url += '&callback=____callback____'
}

scriptElement.src = url

return promise
}

/**
* 移除script标签
* @param scriptElement script dom
*/
function removeScript (scriptElement) {
document.body.removeChild(scriptElement)
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文作者: Leo
  • 本文链接: https://xuebin.me/posts/f72281e3.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!