我正在处理一些本地 json 文件,但我在加载速度方面遇到了一些问题。我的服务器只是一个用 python 制作的小型网络服务器,我通常用它来尝试我的 javascript 代码。 我的脚本只适用于 Firefox,我必须延迟 60000 毫秒(或使用 Firebug )。 脚本是:
function geisson()
{
var iabile = new XMLHttpRequest();
iabile.open("GET", "longanocard.json", true);
iabile.send(null);
PerdiTempo(60000);
var objectjson = {};
var arrayCards= []; //creazione dell'array che conterrà le cards
objectson = JSON.parse(iabile.responseText);
arrayCards = objectson.cards;
//alert(arrayCards[0].__guid__.toSource());
var qwerty = arrayCards[0].__guid__;
var mela = "http://www.airpim.com/png/public/card/" + qwerty + "?width=292";
document.location = mela;
//windows.location.href= mela;
}
PerdiTempo 是我用于延迟的函数:
function PerdiTempo(ms)
{
ms += new Date().getTime();
while (new Date() < ms){}
}
如何加快文件 longanocard.json 的加载速度?为什么延迟不适用于其他浏览器?
最佳答案
你真的应该避免以这种方式等待异步响应(你怎么知道 JSON 解析到底延迟了多少秒?),而是为你的请求使用 onreadystatechange
事件
function geisson() {
var iabile = new XMLHttpRequest();
iabile.onreadystatechange = function(){
if(iabile.readyState === 4 && iabile.status === 200) {
var objectjson = {};
var arrayCards= []; //creazione dell'array che conterrà le cards
objectson = JSON.parse(iabile.responseText);
...
/* codice restante qui */
}
}
iabile.open("GET", "longanocard.json", true);
iabile.send(null);
}
关于javascript - 加快json加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11157030/