Skip to content

Latest commit

 

History

History
45 lines (33 loc) · 2.08 KB

lazy-loading.md

File metadata and controls

45 lines (33 loc) · 2.08 KB

Lazy Loading Routes (En)

Cette page est en cours de traduction française. Revenez une autre fois pour lire une traduction achevée ou participez à la traduction française ici.

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)

Nothing needs to change in the route config, just use Foo as usual:

const router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo }
  ]
})

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')

Webpack will group any async module with the same chunk name into the same async chunk - this also means we don't need to explicitly list dependencies for require.ensure anymore (thus passing an empty array).