Vue Lazy Loading Routes

When building apps with a bundler, the JavaScript bundle can become quite large, and thus affect the page load time. It would be more efficient if we can split each route’s components into a separate chunk, and only load them when the route is visited.

Combining Vue’s async component feature and Webpack’s code splitting feature, it’s trivially easy to lazy-load route components.

All we need to do is define our route components as async components:

const Foo = resolve => {
  // require.ensure is Webpack's special syntax for a code-split point.
  require.ensure(['./Foo.vue'], () => {
    resolve(require('./Foo.vue'))
  })
}

There’s also an alternative code-split syntax using AMD style require, so this can be simplified to:

const Foo = resolve => require(['./Foo.vue'], resolve)

Grouping Components in the Same Chunk

Sometimes we may want to group all the components nested under the same route into the same async chunk. To achieve that we need to use named chunks by providing a chunk name to require.ensure as the 3rd argument:

const Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo')
const Bar = r => require.ensure([], () => r(require('./Bar.vue')), 'group-foo')
const Baz = r => require.ensure([], () => r(require('./Baz.vue')), 'group-foo')

the effect: if you render the component that you visited , this will have more .js files,but not included in vue app.js

这里写图片描述

as the photo show , there will have 2.js and 3.js , if not lazy load only have app.js

这里写图片描述

if you grouping your component in same chunk will the group chunk will have same .js file

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值