[英]How can I load external javascript files using AJAX and know that loading has failed?
我編寫了一個函數,該函數將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>
元素並將其src=
屬性設置為您要加載的文件來通過DOM加載它? 由於是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
一起使用的任何邏輯。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.