How to Lazy Load Routes in Vue for Faster Apps
In Vue, you lazy load routes by using dynamic
import() inside the route's component property. This tells Vue Router to load the component only when the route is visited, reducing initial load time.Syntax
Lazy loading routes in Vue uses dynamic import() inside the route definition. The component property is set to a function that returns the import promise.
path: URL path for the route.component: a function returningimport()to load the component asynchronously.
javascript
const routes = [ { path: '/about', component: () => import('./components/About.vue') } ];
Example
This example shows a Vue Router setup with lazy loaded routes. The About component loads only when the user visits /about. This speeds up the initial page load by not loading About.vue upfront.
javascript
import { createRouter, createWebHistory } from 'vue-router'; const routes = [ { path: '/', component: () => import('./components/Home.vue') }, { path: '/about', component: () => import('./components/About.vue') } ]; const router = createRouter({ history: createWebHistory(), routes }); export default router;
Output
When visiting '/' the Home component loads immediately. When navigating to '/about', the About component loads on demand.
Common Pitfalls
Common mistakes include:
- Using static imports instead of dynamic
import(), which disables lazy loading. - Not returning the import promise from the function, causing errors.
- Forgetting to configure Vue Router properly to support lazy loading.
Always use an arrow function returning import() for lazy loading.
javascript
/* Wrong way - static import disables lazy loading */ import About from './components/About.vue'; const routes = [ { path: '/about', component: About } // This loads About immediately ]; /* Right way - dynamic import for lazy loading */ const routes = [ { path: '/about', component: () => import('./components/About.vue') } ];
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Dynamic import | component: () => import('./MyComponent.vue') | Loads component only when route is visited |
| Static import | import MyComponent from './MyComponent.vue' | Loads component immediately, no lazy loading |
| Vue Router setup | createRouter({ history, routes }) | Required to use lazy loaded routes |
| Route path | path: '/example' | Defines URL path for the route |
Key Takeaways
Use dynamic import() inside a function for the route's component to enable lazy loading.
Lazy loading routes improves app speed by loading components only when needed.
Avoid static imports for route components if you want lazy loading.
Ensure Vue Router is properly configured with createRouter and history mode.
Test routes to confirm components load on demand, not upfront.