|
31 | 31 | - [Route Parameters](#route-parameters) |
32 | 32 | - [Route Query and Name](#route-query-and-name) |
33 | 33 | - [Wildcard Route](#wildcard-route) |
| 34 | + - [Lazy Loading](#lazy-loading) |
34 | 35 |
|
35 | 36 | <!-- END doctoc generated TOC please keep comment here to allow auto update --> |
36 | 37 |
|
@@ -643,3 +644,35 @@ For example, to create 404 page for all paths that aren't explicitly handled, us |
643 | 644 | ```javascript |
644 | 645 | {path: '*', component: NotFound} |
645 | 646 | ``` |
| 647 | + |
| 648 | +### Lazy Loading |
| 649 | + |
| 650 | +Looking at devtools console, entire app is currently being loaded as monolithic app.js file, which loads ALL components (Login, Category, NotFound, etc). These components will be instantiated when a linked path is loaded. |
| 651 | + |
| 652 | +But don't need to load all components up front all at once. Use *lazy loading* to only load a component when a matching route is visited. |
| 653 | + |
| 654 | +To do this, do not import all components in [router.js](src/router.js), define them as async components: |
| 655 | + |
| 656 | +```javascript |
| 657 | +// Components: do not import right away if want to use lazy loading |
| 658 | +// import Category from './theme/Category.vue' |
| 659 | +// import Login from './theme/Login.vue' |
| 660 | +// import NotFound from './theme/NotFound.vue' |
| 661 | + |
| 662 | +// Define components asynchronously to achieve lazy loading |
| 663 | +const Category = () => System.import('./theme/Category.vue') |
| 664 | +const Login = () => System.import('./theme/Login.vue') |
| 665 | +const NotFound = () => System.import('./theme/NotFound.vue') |
| 666 | +``` |
| 667 | + |
| 668 | +Notice webpack output in console after making this change - it generates separate js bundles for each component, separate from app.js: |
| 669 | + |
| 670 | +```shell |
| 671 | +Asset Size Chunks Chunk Names |
| 672 | +assets/js/app.js 395 kB 0 [emitted] [big] app |
| 673 | +assets/js/1.js 9.73 kB 1 [emitted] |
| 674 | +assets/js/2.js 2.58 kB 2 [emitted] |
| 675 | +assets/js/3.js 3.98 kB 3 [emitted] |
| 676 | +``` |
| 677 | + |
| 678 | +Useful as application gets larger, to break it up into chunks and only load what's needed when its needed. |
0 commit comments