Lazy Loading Routes | vue router loading
Whenbuildingappswithabundler,theJavaScriptbundlecanbecomequitelarge,andthusaffectthepageloadtime.Itwouldbemoreefficientifwecanspliteachroutescomponentsintoseparatechunks,andonlyloadthemwhentherouteisvisited.VueRoutersupportsdynamicimports[1]outofthebox,meaningyoucanreplacestaticimportswithdynamicones:js//replace//importUserDetailsfrom./views/UserDetails//withconstUserDetails=()=>import(./views/UserDetails.vue)constrouter=createRouter({//...routes:[{path:/users/:id,component:UserDetails}//...
When building apps with a bundler, the JavaScript bundle can become quite large, and thus affect the page load time. It would be more efficient if we can split each routes components into separate chunks, and only load them when the route is visited.
Vue Router supports dynamic imports[1] out of the box, meaning you can replace static imports with dynamic ones:
js// replace // import UserDetails from ./views/UserDetails // with const UserDetails = () => import(./views/UserDetails.vue) const router = createRouter({ // ... routes: [ { path: /users/:id, component: UserDetails } // or use it directly in the route definition { path: /users/:id, component: () => import(./views/UserDetails.vue) }, ], })The component (and components) option accepts a function that returns a Promise of a component and Vue Router will only fetch it when entering the page for the first time, then use the cached version. Which means you can also have more complex functions a...