新聞中心
創(chuàng)建服務(wù)器
為了方便后續(xù)測試,我們可以使用node創(chuàng)建一個簡單的服務(wù)器。

邵原ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:13518219792(備注:SSL證書合作)期待與您的合作!
服務(wù)器端代碼:
const http = require('http')
const port = 8000;
let list = []
let num = 0
// create 100,000 records
for (let i = 0; i < 100_000; i++) {
num++
list.push({
src: 'https://miro.medium.com/fit/c/64/64/1*XYGoKrb1w5zdWZLOIEevZg.png',
text: `hello world ${num}`,
tid: num
})
}
http.createServer(function (req, res) {
// for Cross-Origin Resource Sharing (CORS)
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "DELETE,PUT,POST,GET,OPTIONS",
'Access-Control-Allow-Headers': 'Content-Type'
})
res.end(JSON.stringify(list));
}).listen(port, function () {
console.log('server is listening on port ' + port);
})const http = require('http')
const port = 8000;
let list = []
let num = 0
// create 100,000 records
for (let i = 0; i < 100_000; i++) {
num++
list.push({
src: 'https://miro.medium.com/fit/c/64/64/1*XYGoKrb1w5zdWZLOIEevZg.png',
text: `hello world ${num}`,
tid: num
})
}
http.createServer(function (req, res) {
// for Cross-Origin Resource Sharing (CORS)
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "DELETE,PUT,POST,GET,OPTIONS",
'Access-Control-Allow-Headers': 'Content-Type'
})
res.end(JSON.stringify(list));
}).listen(port, function () {
console.log('server is listening on port ' + port);
})我們可以使用 node 或 nodemon 啟動服務(wù)器:
$ node server.js
# or
$ nodemon server.js
創(chuàng)建前端模板頁面
然后我們的前端由一個 HTML 文件和一個 JS 文件組成。
Index.html:
Document
Index.js:
// fetch data from the server
const getList = () => {
return new Promise((resolve, reject) => {
var ajax = new XMLHttpRequest();
ajax.open('get', 'http://127.0.0.1:8000');
ajax.send();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
resolve(JSON.parse(ajax.responseText))
}
}
})
}
// get `container` element
const container = document.getElementById('container')
// The rendering logic should be written here.
好的,這就是我們的前端頁面模板代碼,我們開始渲染數(shù)據(jù)。
直接渲染
最直接的方法是一次將所有數(shù)據(jù)渲染到頁面。代碼如下:
const renderList = async () => {
const list = await getList()
list.forEach(item => {
const div = document.createElement('div')
div.className = 'sunshine'
div.innerHTML = `
${item.text}`
container.appendChild(div)
})
}
renderList()一次渲染 100,000 條記錄大約需要 12 秒,這顯然是不可取的。
通過 setTimeout 進(jìn)行分頁渲染
一個簡單的優(yōu)化方法是對數(shù)據(jù)進(jìn)行分頁。假設(shè)每個頁面都有l(wèi)imit記錄,那么數(shù)據(jù)可以分為Math.ceil(total/limit)個頁面。之后,我們可以使用 setTimeout 順序渲染頁面,一次只渲染一個頁面。
const renderList = async () => {
const list = await getList()
const total = list.length
const page = 0
const limit = 200
const totalPage = Math.ceil(total / limit)
const render = (page) => {
if (page >= totalPage) return
setTimeout(() => {
for (let i = page * limit; i < page * limit + limit; i++) {
const item = list[i]
const div = document.createElement('div')
div.className = 'sunshine'
div.innerHTML = `
${item.text}`
container.appendChild(div)
}
render(page + 1)
}, 0)
}
render(page)
}分頁后,數(shù)據(jù)可以快速渲染到屏幕上,減少頁面的空白時間。
requestAnimationFrame
在渲染頁面的時候,我們可以使用requestAnimationFrame來代替setTimeout,這樣可以減少reflow次數(shù),提高性能。
const renderList = async () => {
const list = await getList()
const total = list.length
const page = 0
const limit = 200
const totalPage = Math.ceil(total / limit)
const render = (page) => {
if (page >= totalPage) return
requestAnimationFrame(() => {
for (let i = page * limit; i < page * limit + limit; i++) {
const item = list[i]
const div = document.createElement('div')
div.className = 'sunshine'
div.innerHTML = `
${item.text}`
container.appendChild(div)
}
render(page + 1)
})
}
render(page)
}window.requestAnimationFrame() 方法告訴瀏覽器您希望執(zhí)行動畫,并請求瀏覽器調(diào)用指定函數(shù)在下一次重繪之前更新動畫。該方法將回調(diào)作為要在重繪之前調(diào)用的參數(shù)。
文檔片段
以前,每次創(chuàng)建 div 元素時,都會通過 appendChild 將元素直接插入到頁面中。但是 appendChild 是一項昂貴的操作。
實際上,我們可以先創(chuàng)建一個文檔片段,在創(chuàng)建了 div 元素之后,再將元素插入到文檔片段中。創(chuàng)建完所有 div 元素后,將片段插入頁面。這樣做還可以提高頁面性能。
const renderList = async () => {
console.time('time')
const list = await getList()
console.log(list)
const total = list.length
const page = 0
const limit = 200
const totalPage = Math.ceil(total / limit)
const render = (page) => {
if (page >= totalPage) return
requestAnimationFrame(() => {
const fragment = document.createDocumentFragment()
for (let i = page * limit; i < page * limit + limit; i++) {
const item = list[i]
const div = document.createElement('div')
div.className = 'sunshine'
div.innerHTML = `
${item.text}`
fragment.appendChild(div)
}
container.appendChild(fragment)
render(page + 1)
})
}
render(page)
console.timeEnd('time')
}延遲加載
雖然后端一次返回這么多數(shù)據(jù),但用戶的屏幕只能同時顯示有限的數(shù)據(jù)。所以我們可以采用延遲加載的策略,根據(jù)用戶的滾動位置動態(tài)渲染數(shù)據(jù)。
要獲取用戶的滾動位置,我們可以在列表末尾添加一個空節(jié)點空白。每當(dāng)視口出現(xiàn)空白時,就意味著用戶已經(jīng)滾動到網(wǎng)頁底部,這意味著我們需要繼續(xù)渲染數(shù)據(jù)。
同時,我們可以使用getBoundingClientRect來判斷空白是否在頁面底部。
使用 Vue 的示例代碼:
{{ item.text }}
最后
我們從一個面試問題開始,討論了幾種不同的性能優(yōu)化技術(shù)。
如果你在面試中被問到這個問題,你可以用今天的內(nèi)容回答這個問題,如果你在工作中遇到這個問題,你應(yīng)該先揍那個寫 API 的人。?
文章名稱:如果后端API一次返回10萬條數(shù)據(jù),前端應(yīng)該如何處理?
標(biāo)題網(wǎng)址:http://m.fisionsoft.com.cn/article/codegoc.html


咨詢
建站咨詢
