一、网络请求瀑布效应
网络请求中的瀑布效应(Waterfall Effect)是指多个网络请求按照串行顺序依次执行,后一个请求必须等待前一个请求完成后才能开始,形成类似瀑布般的层叠依赖关系。
1.瀑布效应的表现
在浏览器开发者工具的 Network 面板中,你会看到请求像瀑布一样一个接一个地排列。
csharp
// ❌ 瀑布效应示例
async function loadData() {
const user = await fetchUser() // 1秒
const profile = await fetchProfile(user.id) // 1秒 (等待user完成)
const posts = await fetchPosts(user.id) // 1秒 (等待profile完成)
// 总耗时: 3秒
}
2.常见场景
依赖链式请求
csharp
// 每个请求依赖上一个请求的结果
const userId = await getUserId()
const userData = await getUserData(userId)
const userPermissions = await getPermissions(userData.roleId)
组件嵌套加载
kotlin
// 父组件加载完才能加载子组件数据
ParentComponent mounted → fetch parent data
↓
ChildComponent mounted → fetch child data
↓
GrandchildComponent mounted → fetch grandchild data
资源依赖加载
xml
<!-- HTML加载 → CSS加载 → 字体加载 → 图片加载 -->
<link rel="stylesheet" href="styles.css">
↓
@font-face { url('font.woff2') }
↓
background-image: url('bg.jpg')
二、瀑布效应的危害
1. 危害
瀑布效应的危害
- 页面加载慢:总耗时 = 所有请求时间之和
- 用户体验差:长时间白屏或loading状态
- 资源浪费:网络带宽未充分利用
- 性能瓶颈:成为页面性能的主要限制因素
三、如何优化瀑布效应
1. 并行请求(最常用)
scss
// ✅ 将独立请求改为并行
async function loadData() {
const [user, profile, posts] = await Promise.all([
fetchUser(),
fetchProfile(),
fetchPosts()
])
// 总耗时: 1秒(最慢的那个请求)
}
2. 预加载/预连接
xml
<!-- DNS预解析 -->
<link rel="dns-prefetch" href="https://api.example.com">
<!-- 预连接 -->
<link rel="preconnect" href="https://api.example.com">
<!-- 预加载关键资源 -->
<link rel="preload" href="critical.css" as="style">
3. 资源内联
xml
<!-- 关键CSS内联到HTML中,避免额外请求 -->
<style>
.critical-styles { /* ... */ }
</style>
4. 请求合并
csharp
// ❌ 多次请求
const user1 = await fetchUser(1)
const user2 = await fetchUser(2)
const user3 = await fetchUser(3)
// ✅ 批量请求
const users = await fetchUsers([1, 2, 3])
5. GraphQL(按需获取)
javascript
// 一次请求获取所有需要的数据
const { user, profile, posts } = await graphqlQuery(`
query {
user { id, name }
profile { avatar, bio }
posts { title, content }
}
`)
6. 数据预取
scss
// 在用户操作前提前加载数据
onMouseEnter() {
// 鼠标悬停时预加载下一页数据
prefetchNextPage()
}