2012-06-22 71 views
1

我正在处理一些本地json文件,但我在加载速度方面遇到了一些问题。我的服务器只是一个用python制作的小型网络服务器,我通常用它来尝试我的javascript代码。 我的脚本只适用于Firefox,我必须延迟60000毫秒(或使用萤火虫)。 脚本是:加速json加载

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的负荷?为什么延迟不适用于其他浏览器?

+2

等待响应这种方式是可怕的。你应该使用回调函数,在'onreadystatechange'事件中检查响应状态 – fcalderan

+0

你永远不应该使用这样的循环来编写延迟,因为浏览器在JS代码完成之前不会重新绘制,所以从用户的角度来看,浏览器将会已锁定。 – nnnnnn

回答

2

你真的应该避免等待以这种方式异步响应(你怎么知道多少秒究竟是如何延缓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); 

}