后端响应巨量数据,前端如何避免其性能问题?
有什么性能问题?
-
网络性能
解法1:
可以使用response.body.getReader(); 当收到响应头后就开始读取数据,不能用response.text() or response.json() 这两个方法都是接收整个body数据
// 发送网络请求获取数据
const response = await fetch('your-large-data-url');
// 检查响应状态
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 创建流式读取器
const reader = response.body.getReader();
// 创建UTF-8解码器用于将二进制数据转换为文本
const decoder = new TextDecoder('utf-8');
let done = false;
// 通过流式读取处理大型数据
while (!done) {
// 读取数据块
const { value, done: readerDone } = await reader.read();
done = readerDone;
if (value) {
// 将数据块解码为文本
// stream: true 选项表示这是流式解码,可能还有后续数据
const chunk = decoder.decode(value, { stream: true });
// 输出当前数据块
console.log(chunk);
}
}
解法2:
SSE (Server-Sent Events) 是一种服务器推送技术
-
SSE 是一种服务器向浏览器推送实时数据的技术
-
它建立了一个单向通道,只能从服务器向客户端发送数据
-
使用 HTTP 协议,默认会自动重连
-
相比 WebSocket 更轻量级,适合单向数据推送场景
//Node
app.get('/api/events', (req, res) => {
// 设置 SSE 所需的响应头
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// 发送普通消息
res.write(`data: ${JSON.stringify({msg: '这是一条消息'})}\n\n`);
// 发送带事件类型的消息
res.write(`event: custom-event\ndata: ${JSON.stringify({msg: '这是自定义事件'})}\n\n`);
});
解法3:Websocket
- 渲染性能
- 分页
- 分片渲染
- 虚拟滚动
- canvas