gpt4 book ai didi

javascript - 如何使用 AJAX 加载外部 javascript 文件并知道加载失败?

转载 作者:行者123 更新时间:2023-11-28 07:49:28 25 4
gpt4 key购买 nike

我编写了一个函数,它将 URL 字符串数组作为第一个参数,并尝试使用它们来加载外部脚本。这使我能够链接多个源,以防一个镜像出现故障。

function loadScript(scripts, name, index) {
//Convert single string to array - not effective but easy
if(!(scripts instanceof Array))
scripts = [scripts];
//Use first script src if no name is defined
if(name==null) {
name = scripts[0];
}
//Default index is 0
if(index==null)
index = 0;
//In case wrong index was provided
if(index>=scripts.length)
throw new Error("Aray index out of bounds.");

//Create request
var req = new XMLHttpRequest();
req.open("GET", scripts[index]);
//Execute response text on success
req.onload = function() {
scriptFromString(this.responseText);
}
//Iterate on error
req.onerror = function() {
if(index+1<scripts.length) {
loadScript(scripts, name, index);
}
else {
throw new Error("All sources failed for '"+name+"'.");
}
}
req.send();
}

问题是恼人的 CORS 破坏了这个设计:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://[...].js. This can be fixed by moving the resource to the same domain or enabling CORS.

我该如何克服这个问题?为什么src加载脚本没问题,但ajax请求却抛出错误?

最佳答案

与其尝试使用 XHR 查询获取 js 文件,为什么不通过创建新的 <script> 通过 DOM 加载它呢?元素并设置其 src=属性到您要加载的文件?由于是 DOM,因此跨域加载是合法的。

function loadScript(scripts, name, index) {

//Convert single string to array - not effective but easy
if (!(scripts instanceof Array)) scripts = [scripts];

//Use first script src if no name is defined
if (!name) name = scripts[0];

//Default index is 0
if (!index) index = 0;

//In case wrong index was provided
if (index >= scripts.length) throw "Array index out of bounds.";

//Create request
var include = document.createElement('script');
with(include) {
type = "text/javascript";
src = scripts[index];
onload = function () {
return;
};
onerror = function () {
if (++index < scripts.length) {
loadScript(scripts, name, index);
} else {
throw "All sources failed for '" + name + "'.";
}
};
}
document.head.appendChild(include);
}

(不确定您正在使用 name 参数/变量做什么,所以我将其保留。您可能应该研究您打算使用 name 的任何逻辑。)

关于javascript - 如何使用 AJAX 加载外部 javascript 文件并知道加载失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27017274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com