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 截圖。
相關文章:
1. html5 - 使用angular中,圖片上傳功能中選擇多張圖片是怎么實現的?有什么好的思路嗎?2. javascript - jquery選擇的dom元素如何更新?3. .......4. python - Django問題 ’WSGIRequest’ object has no attribute ’user’5. 數據庫 - mysql boolean型無法插入true6. centos - apache配置django報錯:cannot be loaded as Python modules7. python - flask jinjia2 中怎么定義嵌套變量8. javascript - URL中有#號如何來獲取參數啊? nodejs9. MYSQL 的 SELECT 語句中如何做到判斷字段為空10. javascript - H5頁面無縫輪播
