javascript - 怎么优化多个ajax请求
问题描述
前端页面有五六个ajax请求,一打开那个页面好卡,怎么解决?//fetch异步请求函数 function status(response){ if(response.status>=200 && response.status<300){ return Promise.resolve(response); } else{ return Promise.reject(new Error(response.statusText)); } } function json(response){ return response.json(); } function ctrlset(){ fetch('/cmdopen') .then(status) .then(json) .then(function (data) { console.log(’ok’); }) } //请求数据函数 function getData(){fetch('/numsum') .then(status) .then(json) .then(function (data) {var num = document.getElementById('numbersum');num.innerHTML = data; })//请求风扇是否打开fetch('/feng') .then(status) .then(json) .then(function(data){{# var p = document.getElementById(’fengshan’);#} var feng1 = document.getElementById(’feng1’); var feng0 = document.getElementById(’feng0’); if (data[data.length-1] == 1) { feng1.style.display = 'block'; feng0.style.display = 'none'; }else{ feng1.style.display = 'none'; feng0.style.display = 'block'; } }) //请求宠物是否在屋内fetch('/indoor') .then(status) .then(json) .then(function(data){ var p = document.getElementById(’indoor’); var image1 = document.getElementById(’image1’); var image0 = document.getElementById(’image0’); if(data[data.length-1] == 1){ image0.style.display = 'none'; image1.style.display = 'block'; }else{ image1.style.display = 'none'; image0.style.display = 'block'; } }) .catch(function(err){ console.log('Fetch错误:'+err); }); //请求时间fetch('/time') .then(status) .then(json) .then(function(data){ // 折线图湿度 myChart.setOption({ xAxis:{ data:data} }); }) .catch(function(err){ console.log('Fetch错误:'+err); });//请求温度数据fetch('/tem') .then(status) .then(json) .then(function(data){ //折线图温度 myChart.setOption({ series: [{ // 根据名字对应到相应的系列 name: ’TEM’, data: data }] }); }) .catch(function(err){ console.log('Fetch错误:'+err); });//请求湿度数据 fetch('/hum').then(status).then(json).then(function(data){ // 折线图湿度 myChart.setOption({ series: [{ // 根据名字对应到相应的系列 name: ’HUM’, data: data }] });}).catch(function(err){ console.log('Fetch错误:'+err);}); } //定时更新数据 setInterval(’getData()’,10);
问题解答
回答1:setInterval(’getData()’,10);
你十毫秒抓一次数据能不卡么。数据还没回来又发了2个出去了 无穷延续
回答2:先确定页面卡顿的问题。
页面卡一般都是DOM渲染的问题,F12查查就懂了,不要把锅都甩给ajax,比如说你ajax一个html过来,再渲染,那肯定很卡。
回答3:跟ajax数量可能有关系,但应该不是主要原因,因为毕竟ajax是异步的,慢还是获取数据量比较大的原因吧,如果是一下子获取数据量比较大的情况的话,建议你们分批次加载,不要一下子取所有数据;
如果是ajax太多的情况,那么可以适当的分段加载,比如原先6个ajax,分成两段,第一段的三个ajax加载好了,再加载下一段
回答4:页面初始化的时候 如果代码不可避免 则加loadding解决
回答5:使用Promise做延迟处理.
回答6:请题主发页面代码,最好附带 Chrome 的 Timing 截图。
相关文章:
