35 lines
1.4 KiB
TypeScript
35 lines
1.4 KiB
TypeScript
import type { Router } from 'vue-router'
|
|
|
|
/**
|
|
* 路由懒加载 chunk 预取
|
|
*
|
|
* 页面均为动态 import(每页独立 chunk,见 src/router/index.ts),首次进入某页
|
|
* 需现场从线上拉取 chunk。菜单 hover 时提前触发 import()(结果被 router 缓存,
|
|
* 点击时直接命中缓存),弱网下显著减少"点了没反应/跳转慢"的等待时间。
|
|
*/
|
|
|
|
/** 触发目标路由的懒加载 chunk 预取;href 为空或预取失败时静默(点击时会走 onError 兜底) */
|
|
export function prefetchRouteChunk(router: Router, href?: string): void {
|
|
if (!href) return
|
|
let target = href.trim()
|
|
const hashIndex = target.indexOf('#')
|
|
if (hashIndex >= 0) {
|
|
target = target.slice(0, hashIndex)
|
|
}
|
|
try {
|
|
const resolved = router.resolve(target)
|
|
const component = resolved.matched[0]?.components?.default as unknown
|
|
// 懒加载路由的 default 是 () => import(...) 加载器:调用即触发 chunk 下载(结果被 vue-router 缓存)
|
|
if (typeof component === 'function') {
|
|
const result = (component as () => unknown)()
|
|
if (result && typeof (result as Promise<unknown>).then === 'function') {
|
|
void (result as Promise<unknown>).catch(() => {
|
|
/* 预取失败静默,点击时统一由 router.onError 兜底 */
|
|
})
|
|
}
|
|
}
|
|
} catch {
|
|
/* 路径无法解析时忽略 */
|
|
}
|
|
}
|