loyjers
loyjers
  • 发布:2015-03-17 21:24
  • 更新:2015-07-21 17:44
  • 阅读:2894

继续问:没人发现XMLHttpRequest发送请求响应速度慢的问题吗?

分类:HTML5+
var xhr = new plus.net.XMLHttpRequest();  
    var stime1 = new Date().getTime();   
    xhr.onreadystatechange = function () {  
        switch ( xhr.readyState ) {  
            case 0:  
                stime = new Date().getTime()-stime1;console.log('time0 : '+stime+' ms');  
                console.log( "xhr请求已初始化" );  
                break;  
            case 1:  
                stime = new Date().getTime()-stime1;console.log('time1 : '+stime+' ms');  
                console.log( "xhr请求已打开" );  
                break;  
            case 2:  
                stime = new Date().getTime()-stime1;console.log('time2 : '+stime+' ms');  
                console.log( "xhr请求已发送" );  
                break;  
            case 3:  
                //console.log(xhr.getAllResponseHeaders());  
                stime = new Date().getTime()-stime1;console.log('time3 : '+stime+' ms');  
                console.log( "xhr请求已响应");  
                break;  
            case 4:  
                stime = new Date().getTime()-stime1;console.log('time4 : '+stime+' ms');  
                if ( xhr.status == 200 ) {  
                    console.log( "xhr请求成功:"+xhr.responseText );  
                } else {   
                    console.log( "xhr请求失败:"+xhr.readyState );  
                }  
                break;  
            default :  
                break;  
        }  
    }  
    xhr.open( "GET", "http://www.baidu.com");  
    xhr.send();

得出结论是,XMLHttpRequest对象发送完请求,到得到响应这段事件最耗时,从100毫秒到4秒不等,我测试本地局域网服务器,服务端执行事件不到10毫秒,这个时间无法缩短的话,APP的用户体验简直无法忍受,每次从服务器取数据都要花1-3秒。

打印出来的不同阶段的日志:

[LOG] :time1 : 0 ms
[LOG] : xhr请求已打开
[LOG] : time2 : 1 ms
[LOG] : xhr请求已发送
[LOG] : time3 : 237 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 240 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 251 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 252 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 253 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 253 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 259 ms
[LOG] : xhr请求已响应
[LOG] : time4 : 260 ms
[LOG] : xhr请求成功:<!DOCTYPE html>

[LOG] : time1 : 1 ms
[LOG] : xhr请求已打开
[LOG] : time2 : 2 ms
[LOG] : xhr请求已发送
[LOG] : time3 : 556 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 557 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 562 ms
[LOG] : xhr请求已响应
[LOG] : time : 1426597778347 ms
[LOG] : time3 : 1248 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 1481 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 1484 ms
[LOG] : xhr请求已响应
[LOG] : time3 : 1542 ms
[LOG] : xhr请求已响应
[LOG] : time4 : 1543 ms
[LOG] : xhr请求成功:<!DOCTYPE html>

2015-03-17 21:24 负责人:无 分享
已邀请:
太阳光

太阳光

这跟你的宽带有关,本人测试都是在500ms内完成,算可以啦。

mis

mis - 前端攻城

我也发现比较慢,10m电信,无其他使用的情况下。
不知道是不是跨域的原因。

ItsPaster

ItsPaster

4G 網路下,自家服務器平均低於150ms
感覺還行,應該跟XMLHttpRequest無關。。。

网络小白鼠

网络小白鼠

我本地也有类似的问题,请求时快时慢。

该问题目前已经被锁定, 无法添加新回复