import type { RouteRecordRaw } from 'vue-router'
* 路由预加载工具
* 在空闲时预加载可能即将访问的路由组件,提升页面切换速度
*/
export type PrefetchStrategy = 'hover' | 'visible' | 'idle'
const prefetchedPaths = new Set<string>()
* 使用 requestIdleCallback 预加载路由组件
* 在浏览器空闲时执行,不影响主要交互
*/
export function prefetchRoute(componentPath: string): void {
if (prefetchedPaths.has(componentPath)) return
const normalized = componentPath.replace(/\\/g, '/')
const loaders = import.meta.glob('@/views/**/*.vue')
const loader = loaders[`/src/views/${normalized}.vue`] || loaders[`./src/views/${normalized}.vue`]
if (loader) {
prefetchedPaths.add(componentPath)
if ('requestIdleCallback' in window) {
;(window as any).requestIdleCallback(() => loader())
} else {
setTimeout(() => loader(), 200)
}
}
}
* 预加载一组路由
*/
export function prefetchRoutes(paths: string[]): void {
paths.forEach(prefetchRoute)
}
* 判断路由是否已预加载
*/
export function isPrefetched(path: string): boolean {
return prefetchedPaths.has(path)
}