Vue.js Lazy Loading Routes
Lazy loading routes delays the download of a page's code until a visitor opens that page. A normal build bundles every page into one large JavaScript file, and the browser must download all of it before the first screen appears. Lazy loading splits the bundle into small pieces. The home page loads quickly, and other pages arrive on demand.
Think of a restaurant kitchen. A chef does not cook every dish on the menu before guests arrive. The kitchen prepares each dish when someone orders it. Lazy loading prepares each page when a visitor requests it.
Eager Loading: The Default Problem
Static imports pull every page into the starting bundle.
import Home from "./views/Home.vue";
import Reports from "./views/Reports.vue";
import Settings from "./views/Settings.vue";
import Admin from "./views/Admin.vue";
const routes = [
{ path: "/", component: Home },
{ path: "/reports", component: Reports },
{ path: "/settings", component: Settings },
{ path: "/admin", component: Admin }
];Diagram: One Large Bundle
app.js (900 KB) +-- Home +-- Reports +-- Settings +-- Admin Visitor opens "/" --> browser downloads all 900 KB first
Lazy Loading with Dynamic Imports
Replace the static import with an arrow function that calls import(). The build tool sees each dynamic import and creates a separate file, called a chunk.
const routes = [
{ path: "/", component: () => import("./views/Home.vue") },
{ path: "/reports", component: () => import("./views/Reports.vue") },
{ path: "/settings", component: () => import("./views/Settings.vue") },
{ path: "/admin", component: () => import("./views/Admin.vue") }
];Vue Router calls the function only when a visitor navigates to that route, then caches the downloaded result for later visits.
Diagram: Split Bundles
app.js (150 KB) --> loads at start Home.js (40 KB) --> loads for "/" Reports.js (220 KB) --> loads when "/reports" opens Settings.js (60 KB) --> loads when "/settings" opens Admin.js (430 KB) --> loads when "/admin" opens
A visitor who never opens the admin area never downloads its 430 KB.
Group Related Pages into One Chunk
Many small files create many network requests. A build tool setting can merge related pages. Vite uses Rollup, and its manualChunks option names the groups.
// vite.config.js
export default {
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ["vue", "vue-router", "pinia"]
}
}
}
}
};Libraries that rarely change sit in a vendor chunk. Browsers keep that file in cache across updates to your own code.
Show Feedback While a Chunk Loads
A slow connection delays the download, and a blank screen confuses visitors. A global loading flag fills the gap using router hooks.
import { ref } from "vue";
export const loading = ref(false);
router.beforeEach(() => { loading.value = true; });
router.afterEach(() => { loading.value = false; });
<div v-if="loading" class="loader">Loading...</div>
<RouterView />Diagram: Loading Sequence
Click link | beforeEach --> loading = true (spinner shows) | chunk downloads | afterEach --> loading = false (page shows)
Handle Download Failures
Network drops can break a chunk download. The router reports the failure through router.onError.
router.onError((error) => {
console.error("Page failed to load", error);
alert("The page could not load. Check your connection and try again.");
});After a new deployment, old chunk file names disappear from the server. A visitor with an open tab may hit this error, and a prompt to reload the page solves it.
Prefetch Likely Pages
Build tools can add hints that download likely next pages while the browser is idle. Reserve this for the pages most visitors use after the home page, such as a login or product list.
Best Practices
- Load the home page and any tiny layout components eagerly.
- Lazy load heavy pages, such as charts, editors, and admin tools.
- Check the build report to see chunk sizes.
- Test on a throttled connection in browser developer tools.
Summary
Lazy loading routes uses dynamic import() to split an application into chunks that load on demand. Initial load shrinks, and unused pages cost nothing. Group stable libraries into vendor chunks, show a loading indicator during downloads, and handle errors with router.onError. Heavy pages benefit the most.
