使用流式处理来提升页面性能
Astro 的 SSR 使用 HTML 流式处理来在组件可用时将其发送到浏览器,以便更快地加载页面。为了进一步提升你的页面性能,你可以策略性地构建你的组件,即通过避免阻塞的数据获取来优化它们的加载速度。
如下的重构示例演示了如何通过将获取调用移动到其他组件,并将它们从阻塞页面渲染的组件中迁移出来,以提高页面性能。
以下页面在 frontmatter 中会 await
一些数据。而 Astro 会等待所有的 fetch 调用解决后,再将 HTML 发送到浏览器。
---const personResponse = await fetch('https://randomuser.me/api/');const personData = await personResponse.json();const randomPerson = personData.results[0];const factResponse = await fetch('https://catfact.ninja/fact');const factData = await factResponse.json();---<html> <head> <title>A name and a fact</title> </head> <body> <h2>A name</h2> <p>{randomPerson.name.first}</p> <h2>A fact</h2> <p>{factData.fact}</p> </body></html>