vue3 路由加载慢的问题

5 阅读1分钟

最近写了一个vue3的管理端页面,发现每次重启或者部署到测试环境,nprogress进度条走完了 页面还要卡个一两秒才加载出来,严重影响体验 于是在路由里加了个组件预加载的逻辑

function preloadRouteComponents() {
  const queue = [...constantRouter];
  while (queue.length) {
    const route = queue.shift();
    if (!route) continue;

    if (Array.isArray(route.children) && route.children.length) {
      queue.push(...route.children);
    }

    const loader = route.component;
    if (typeof loader === 'function') {
      try {
        const loadTask = loader();
        if (loadTask && typeof loadTask.then === 'function') {
          loadTask.catch(() => {});
        }
      } catch (error) {
        console.warn(
          '[router] preload route component failed:',
          route.path,
          error
        );
      }
    }
  }
}

function scheduleRoutePreload() {
  if (hasPreloadedRouteChunks) return;
  hasPreloadedRouteChunks = true;

  const runPreload = () => preloadRouteComponents();
  if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
    window.requestIdleCallback(runPreload, { timeout: 2000 });
  } else {
    setTimeout(runPreload, 300);
  }
}

上述两个方法一加 体验丝滑 再也没有那种卡顿压抑感