如何让script 标签里的多个为外网网址的src属性 按顺序执行
时间: 2023-05-22 21:01:49 浏览: 55
您可以使用 JavaScript 中的 Promise.all() 方法来按顺序执行多个外部脚本。首先,将所有脚本的 URL 存储在一个数组中,然后使用 Array.map() 方法将它们转换为 Promise 对象。接下来,使用 Promise.all() 方法将所有 Promise 对象组合成一个 Promise 对象,然后使用 .then() 方法来处理它们的结果。以下是示例代码:
```javascript
const urls = [
'https://example.com/script1.js',
'https://example.com/script2.js',
'https://example.com/script3.js'
];
Promise.all(
urls.map(url => {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
})
).then(() => {
console.log('All scripts have been loaded.');
}).catch(error => {
console.error('An error occurred while loading the scripts:', error);
});
```
请注意,这种方法需要所有脚本都成功加载才能继续执行。如果其中一个脚本加载失败,整个 Promise 对象将被拒绝,并且将跳过后续的 .then() 方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)