Lazy Loading with Routing - LoadComponent, Child Routes
What is Lazy Loading?
Lazy loading means load a page only when it is needed.
By default, Angular loads all pages together, which can make the app slow.
Why Lazy Loading is Important?
- Big projects have many pages
- Rarely used pages (Admin, FAQ, Settings) should not load by default
- Loading everything increases:
- App size
- Load time
- Network requests
- Server cost
Default Angular Behavior
All components load together on app start.
Even if the user never opens that page, it is already loaded.
Lazy Loading Concept
- Frequently used pages → normal load (Home, Login)
- Rarely used pages → lazy load (User, Admin, Settings)
How to Apply Lazy Loading (Parent Component)
Before (Normal Route)
{
path: 'user',
component: User
}
After (Lazy Loaded Route)
{
path: 'user',
loadComponent: () =>
import('./pages/user/user')
.then(c => c.User)
}
componentis removedloadComponentis used- Component loads only when route is visited
Result in Browser
- On refresh → User page is NOT loaded
- When clicking User → User component loads
Lazy Loading Multiple Pages (Example: Admin)
Normal Route
{
path: 'admin',
component: Admin
}
Lazy Loaded Admin Route
{
path: 'admin',
loadComponent: () =>
import('./pages/admin/admin')
.then(c => c.Admin)
}
Now Admin loads only when Admin menu is clicked
Lazy Loading Child Components
Lazy loading on parent does NOT apply automatically to child components.
You must apply lazy loading manually on child routes.
Example: User → Setting (Lazy Loaded Child)
{
path: 'setting',
loadComponent: () =>
import('./pages/setting/setting')
.then(c => c.Setting)
}
Example: User → Profile (Lazy Loaded Child)
{
path: 'profile',
loadComponent: () =>
import('./pages/profile/profile')
.then(c => c.Profile)
}
Important Behavior
- If you refresh on a route, that component loads
- Lazy loading works only for not-yet-visited routes