网络请求瀑布效应

一、网络请求瀑布效应

网络请求中的瀑布效应(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. 危害

瀑布效应的危害

  1. 页面加载慢:总耗时 = 所有请求时间之和
  2. 用户体验差:长时间白屏或loading状态
  3. 资源浪费:网络带宽未充分利用
  4. 性能瓶颈:成为页面性能的主要限制因素

三、如何优化瀑布效应

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()
}
相关推荐
We་ct1 天前
LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置:二分查找实战
前端·算法·leetcode·typescript·二分
Nan_Shu_6141 天前
学习:Cesium (4)
前端·学习
Loadings1 天前
聊聊 AI Coding 的最新范式:Harness Engineering:我们这群程序员,又要继续学了?
前端·后端
ssshooter1 天前
哈希是怎么被破解的?
前端·后端
蜡台1 天前
Vue 中多项目的组件共用方案
前端·javascript·vue.js·git
笨笨狗吞噬者1 天前
【uniapp】微信小程序实现自定义 tabBar
前端·微信小程序·uni-app
恋猫de小郭1 天前
React Native 鸿蒙 2026 路线发布,为什么它的适配成本那么高?
android·前端·react native
呆头鸭L1 天前
Electron进程通信
前端·javascript·electron·前端框架·vue
splage1 天前
spring-boot-starter和spring-boot-starter-web的关联
前端
张元清1 天前
使用 Hooks 构建无障碍 React 组件
前端·javascript·面试