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?

  1. Big projects have many pages
  2. Rarely used pages (Admin, FAQ, Settings) should not load by default
  3. Loading everything increases:
  4. App size
  5. Load time
  6. Network requests
  7. 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

  1. Frequently used pages → normal load (Home, Login)
  2. 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)
}
  1. component is removed
  2. loadComponent is used
  3. Component loads only when route is visited

Result in Browser

  1. On refresh → User page is NOT loaded
  2. 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

  1. If you refresh on a route, that component loads
  2. Lazy loading works only for not-yet-visited routes