Lazy loading routes means loading parts of your app only when needed. This helps your app start faster and saves data.
0
0
Lazy loading routes in Vue
Introduction
When your app has many pages and you want faster start time.
When some pages are rarely visited and don't need to load upfront.
When you want to reduce the initial download size for users.
When you want to improve user experience on slow networks.
Syntax
Vue
const routes = [ { path: '/home', component: () => import('./components/Home.vue') }, { path: '/about', component: () => import('./components/About.vue') } ];
Use a function that returns import() to load the component only when the route is visited.
This syntax works with Vue Router and modern JavaScript modules.
Examples
Lazy load the Dashboard component only when the user visits '/dashboard'.
Vue
const routes = [ { path: '/dashboard', component: () => import('./Dashboard.vue') } ];
Add a comment to name the chunk for better debugging and caching.
Vue
const routes = [ { path: '/profile', component: () => import(/* webpackChunkName: "profile" */ './Profile.vue') } ];
Sample Program
This Vue Router setup lazy loads the Home and About components. They load only when you visit their routes, making the app start faster.
Vue
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;
OutputSuccess
Important Notes
Lazy loading improves app speed but adds a small delay when loading a new route for the first time.
Use lazy loading for large or rarely used components to save bandwidth.
Check browser DevTools Network tab to see when chunks load.
Summary
Lazy loading routes loads components only when needed.
This reduces initial app size and speeds up start time.
Use component: () => import('...') syntax in Vue Router.