Lazy loading

In this guide, we will explore lazy loading code in UI-Router.

Lazy loading is the practice of loading expensive resources on-demand. Instead of loading all application resources before the app is bootstraped, a lazy loaded resource is fetched just-in-time, when the resource is required.

This practice can greatly reduce the initial startup time for single page web applications. Instead of sending all of the application’s code to the browser before the app starts, the code can be split up into smaller chunks (modules), which are then lazy loaded as needed.

Split into modules

To use lazy loading, the application should first be split up into chunks, or modules. Each module will be loaded independently of the others.

The simplest way to split an application into modules is by application feature. If your application has a Messages feature, a Contacts feature, and a TODO feature, each of these features would be an module, ready to be lazy loaded.

Beside the feature modules, there is also the initial code used to bootstrap the app, which is not lazy loaded.

    +--------------------------------+
    |                                |
    |       Initial code             |
    | (Bootstrap and basic app code) |
    |                                |
    +--------------------------------+

+--------------------------------------------+

          LAZY LOADED FEATURE MODULES

    +-------------+          +----------+
    |             |          |          |
    |  Contacts   |          |   TODO   |
    |             |          |          |
    +-------------+          +----------+
                +------------+
                |            |
                |  Messages  |
                |            |
                +------------+

Each feature module contains the code necessary to implement the feature. This may include:

  • States
    • Top level state, e.g., contacts
    • Nested states, e.g., contacts.list, contacts.edit, contacts.view
  • Routed components
    • The view(s) for the states, e.g., ListContacts, ViewContact, EditContact
  • Non-routed components/directives
    • Any additional components used to implement the feature, e.g., ContactProfileImage
  • Service code
    • Other code necessary to implement the feature

#