title | layout | excerpt | sitemap | permalink |
---|---|---|---|---|
Lazy loading |
single |
UI-Router: Lazy loading states and modules |
true |
/guide/lazyloading |
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. {: .notice--info}
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.
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
- Top level state, e.g.,
- Routed components
- The view(s) for the states, e.g.,
ListContacts
,ViewContact
,EditContact
- The view(s) for the states, e.g.,
- Non-routed components/directives
- Any additional components used to implement the feature, e.g.,
ContactProfileImage
- Any additional components used to implement the feature, e.g.,
- Service code
- Other code necessary to implement the feature
Create a config function and provide your state config there.
export default angular
.module('lazyLoadedModule', ['ui.router'])
.component('lazy', {
restrict: 'E',
template: '<div>lazy loaded</div>',
})
.name;
export default function($stateProvider) {
'ngInject';
$stateProvider.state('lazy', {
component: 'lazyLoaded',
resolve: {
loadModule: function($q, $ocLazyLoad) {
'ngInject';
const d = $q.defer();
require.ensure([], function() {
const waiting = require('./lazy');
$ocLazyLoad.load({name: waiting.default});
d.resolve(waiting.default);
});
return d.promise;
},
},
});
}
Simply add it to your angular app
import lazy_load_state from './lazy.config
angular
.module('app', [
'oc.lazyLoad',
'ui.router'
])
.config(lazy_load_state)
.component('app', AppComponent);