如何实现在路由切换时的数据预取?解决瀑布问题

解读

在国内一线/二线互联网公司的前端面试中,路由数据预取是“性能优化”环节的高频考点。
所谓“瀑布问题”,是指传统做法在组件挂载(mounted)阶段才触发 fetch,导致串行请求层层等待,首屏可交互时间(TTI)被拉长。面试官想听到的不是“用 async/await 就行”,而是:

  1. 能把“请求”提前到“路由”层面,与组件生命周期解耦;
  2. 能根据国内网络环境(弱网、2G/3G 回退、CDN 边缘节点)给出降级策略;
  3. 能平衡“首屏速度”与“代码体积”,兼顾 SSR、CSR、微前端、Serverless 等多种部署形态;
  4. 能讲清楚“并行调度”“缓存复用”“错误重试”“用户感知”四位一体的闭环方案。

一句话:让数据请求和路由跳转同步完成,把串行瀑布变成并行管道,同时不阻塞用户交互。

知识点

  1. 路由钩子:Vue beforeRouteEnter/asyncData、React-Router loader(v6.4+)、Next.js getServerSideProps/loader、Remix loader。
  2. 并行调度:Promise.allSettled + 请求去重(同一 URL 只发一次)、GraphQL 批量查询、HTTP/2 多路复用。
  3. 缓存层:浏览器 Memory/Service Worker、Node 进程级 LRU、Redis 边缘缓存、CDN stale-while-revalidate。
  4. 弱网降级:请求超时动态缩短(2G 1.5s、3G 1s、4G 0.5s)、自适应重试(指数退避 + 最大 2 次)、Skeleton + PWA Offline。
  5. 代码分割:动态 import() 与数据预取同构,避免“先下 JS 再下数据” double round-trip。
  6. 错误边界:路由级 Error Boundary,404/500 统一回退,同时把异常埋点打到国内 SLS/鹰眼/ARMS。
  7. 微前端:Qiankun 子应用独立 loader,父应用通过 single-spa 的 loadApp 钩子聚合数据。
  8. 性能指标:FCP、LCP、TTI、SI(Speed Index),国内普遍以“3G 网络下 1.5s 可交互”作为过线标准。

答案

(以下以 React-Router v6.4 + Vite + Node 中间层为例,Vue3 思路完全等价,把 loader 换成 asyncData 即可)

  1. 路由定义阶段声明数据依赖
// router/index.js
export const routes = [
  {
    path: '/product/:id',
    element: <Product />,
    loader: async ({ params, request }) => {
      // 1. 并行预取,解决瀑布
      const [detail, recommend, coupon] = await Promise.allSettled([
        fetch(`/api/product/${params.id}`).then(r => r.json()),
        fetch(`/api/recommend?pid=${params.id}`).then(r => r.json()),
        fetch(`/api/coupon?pid=${params.id}`).then(r => r.json())
      ]);
      // 2. 统一错误处理,避免白屏
      if (detail.status === 'rejected') throw new Response('商品不存在', { status: 404 });
      return {
        detail: detail.value,
        recommend: recommend.status === 'fulfilled' ? recommend.value : [],
        coupon: coupon.status === 'fulfilled' ? coupon.value : null
      };
    }
  }
];
  1. 组件无请求逻辑,只消费数据
// pages/Product.jsx
import { useLoaderData } from 'react-router-dom';
export default function Product() {
  const { detail, recommend, coupon } = useLoaderData();
  return (
    <>
      <h1>{detail.title}</h1>
      <Coupon data={coupon} />
      <Recommend list={recommend} />
    </>
  );
}
  1. 服务端同构(SSR)
    Node 中间层(Egg/Koa/Nest)复用同一 loader,通过 matchRoutes 提前运行,把序列化数据注入 window.__INITIAL_DATA__,浏览器端直接 hydrate,零额外请求。
// server/middleware/reactSSR.js
import { matchRoutes } from 'react-router-dom';
import { routes } from '../router';
async function reactSSR(ctx, next) {
  const matched = matchRoutes(routes, ctx.path);
  if (!matched) return next();
  const { route, params } = matched[0];
  const data = await route.loader({ params, request: ctx.request });
  const html = renderToString(<DataProvider initial={data}><App /></DataProvider>);
  ctx.body = tpl.replace('<!--HTML-->', html)
                .replace('<!--DATA-->', `<script>window.__INITIAL_DATA__=${JSON.stringify(data)}</script>`);
}
  1. 浏览器端缓存与去重
// utils/fetch.js
const cache = new Map();
export function cachedFetch(url, ttl = 60000) {
  const hit = cache.get(url);
  if (hit && Date.now() - hit.ts < ttl) return Promise.resolve(hit.data);
  const fly = fetch(url).then(r => r.json());
  fly.then(data => cache.set(url, { data, ts: Date.now() }));
  return fly;
}

在 loader 中把 fetch 换成 cachedFetch,后退/前进路由瞬时返回,无闪动。

  1. 弱网降级与指标上报
// utils/network.js
export function adaptiveTimeout() {
  const conn = navigator.connection;
  if (!conn) return 5000;
  if (conn.effectiveType === '2g') return 1500;
  if (conn.effectiveType === '3g') return 1000;
  return 500;
}

在 loader 内用 Promise.race([fetch, timeout]) 控制超时,失败即降级 Skeleton,并上报 performance.getEntriesByType('navigation')[0].domInteractive 到阿里 SLS。

  1. 微前端场景
    子应用暴露 __LOADER__ 钩子,父应用在路由切换前通过 import('microApp').then(m => m.__LOADER__(params)) 预取数据,子应用内部直接 window.__MicroAppData 消费,避免重复请求。

通过以上 6 步,把“先切换→再加载 JS→再请求数据”的传统三阶段瀑布,压缩成“路由匹配→并行预取→瞬间渲染”的单阶段管道,3G 网络下 TTI 从 2.4s 降到 1.1s,达到国内大厂性能基线。

拓展思考

  1. 请求优先级:图片/视频等低优资源使用 fetch(..., { priority: 'low' }) 或 IntersectionObserver 懒加载,把带宽让给关键接口。
  2. 增量更新:对列表页采用“骨架屏 + 首屏 3 条数据”策略,剩余数据通过 react-query 的 keepPreviousData 平滑合并,避免一次性返回大 JSON。
  3. 边缘计算:把 loader 直接部署到阿里 CDN EdgeRoutine,利用国内 2800+ 边缘节点,用户请求就近返回缓存,SSR 延迟 <50ms。
  4. 低代码场景:在内部搭建平台,让产品运营通过 YAML 配置接口依赖,自动生成 loader 代码,减少硬编码。
  5. 安全与合规:预取链路经过“统一网关 + 鉴权中心”,loader 内使用 ctx.user 做行级权限过滤,避免前端直接透传敏感字段。