懒加载在偷懒?
为了加速应用启动时间,一般我们会对代码进行分割,以便减少应用启动体积,被分割的代码会在需要时候才会被加载进来,通常做法是将其他路由入口的代码分割出来,按需加载一般被称作懒加载
。
不过,懒加载非常懒,如果不触发对应的事件,资源文件是不会被加载进来的。这就有可能从首页进入其它页面时候,需要发起多次加载(资源&数据)。
预加载
在首屏渲染完毕之后,网络已然处理空闲状态,我们可以通过将分割的代码进行预加载,以提高用户进入二级入口时体验,一般来说是这样的:
// route.js
const HomePage = () => import('@/pages/home')
const AboutPage = () => import('@/pages/about')
const ErrorPage = () => import('@/pages/error')
...
new Router({
route: [{
path: '/home',
component: HomePage,
}, {
path: '/about',
component: AboutPage,
}, {
path: '/Error',
component: ErrorPage,
}, {
...
}]
})
// home.js
// ...all rendered
import('@/pages/about')
import('@/pages/error')
...
这种方式会造成不少的代码冗余&代码入侵,在多入口应用要做到预加载需要做非常繁琐的操作。通过loder
可以非常轻松地进行资源预加载:
// route.js
loder('HomePage', () => import('@/pages/home'))
...
new Router({
route: [{
path: '/home',
component: () => loder.echo('HomePage'),
}, {
...
}]
})
// index.js
// ...all rendered
loder.loadMatch('Page')