For a Single Page Application (SPA), when building, the JavaScript package can become very large, affecting page load speed. The components corresponding to different routes are split into different code blocks. Then, when a route is accessed, the corresponding component is loaded, which is called route lazy loading.
Vue allows you to define your components using a factory function. This factory function will asynchronously resolve your component definition. Vue will only trigger this factory function when the component needs to be rendered, and will cache the result for future re-rendering.
This factory function will receive a resolve callback. This callback function will be called when you receive the component definition from the server, and reject(reason) can also be called to indicate a failed load. The setTimeout here is just used to demonstrate the asynchronous transfer of component definition. Combining asynchronous components with webpack's code-splitting functionality can achieve lazy loading of components.
You can also return a Promise in the factory function, combining webpack 2 and ES2015 syntax.
In fact, in the configuration of Vue-Router, you can directly combine Vue's asynchronous components with Webpack's code-splitting feature to achieve lazy loading of route components, with each component generating a separate js file after packaging.
In Webpack2, you can use dynamic import syntax to define code split points. This method is also recommended by the official. If using Babel, you need to add the syntax-dynamic-import plugin to allow Babel to correctly parse the syntax.
Sometimes, we may want to package all components under a certain route in the same asynchronous chunk. You need to use a special comment syntax to provide a chunk name when using webpack > 2.4.
In fact, in the configuration of Vue-Router, you can directly define lazy loading.
require.ensure provided by webpackUsing webpack's require.ensure can also achieve on-demand loading, and specifying the same chunkName for multiple routes will also merge and package them into a single js file.