Skip to content

Commit f1561d2

Browse files
committed
[docs] async route loading
1 parent dea4a19 commit f1561d2

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

docs/en/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
- [Router Options](options.md)
1111
- [router-view](view.md)
1212
- [v-link](link.md)
13+
- [Lazy loading Routes](lazy.md)
1314
- [Transition Pipeline](pipeline/README.md)
1415
- [Transition Hooks](pipeline/hooks.md)
1516
- [data](pipeline/data.md)

docs/en/lazy.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Lazy Loading Routes
2+
3+
When you are using bundlers like Webpack or Browserify, it's trivially easy to lazy-load a route component using Vue.js' built-in [async component functionality](http://vuejs.org/guide/components.html#Async_Components). Instead of directly defining your route component, you define it as a function that will asynchronously resolve the actual component definition:
4+
5+
``` js
6+
router.map({
7+
'/async': {
8+
component: function (resolve) {
9+
// somehow retrieve your component definition from server...
10+
resolve(MyComponent)
11+
}
12+
}
13+
})
14+
```
15+
16+
Now, manually handling component retrieval is less than ideal, but bundlers like Webpack & Browserify both provides ways to make it easier.
17+
18+
### Webpack
19+
20+
Webpack has built-in support for async code-splitting. You can use the AMD-like `require` syntax in your code to indicate an async code-split point:
21+
22+
``` js
23+
require(['./MyComponent.vue'], function (MyComponent) {
24+
// code here runs after MyComponent.vue is asynchronously loaded.
25+
})
26+
```
27+
28+
Combined with the router it can simply look like this:
29+
30+
``` js
31+
router.map({
32+
'/async': {
33+
component: function (resolve) {
34+
require(['./MyComponent.vue'], resolve)
35+
}
36+
}
37+
})
38+
```
39+
40+
Now, `MyComponent.vue`, along with any dependencies that is only used by itself, will be loaded asynchronously only when the route `/async` needs to be rendered.
41+
42+
### Browserify
43+
44+
It's a bit more tricky to achieve the same with Browserify, but it's possible with the [`partition-bundle` plugin](https://github.com/substack/browserify-handbook/blob/master/readme.markdown#partition-bundle). You will have to manually declare your bundle mappings in a `json` file:
45+
46+
``` json
47+
{
48+
"main.js": ["./main.js"],
49+
"my-component.js": ["./MyComponent.vue"]
50+
}
51+
```
52+
53+
Then in `main.js` you would do something similar, using the `loadjs` function instead of `require`:
54+
55+
``` js
56+
router.map({
57+
'/async': {
58+
component: function (resolve) {
59+
loadjs(['./MyComponent.vue'], resolve)
60+
}
61+
}
62+
})
63+
```

0 commit comments

Comments
 (0)