Lazy loading in AngularJS allows modules to be loaded on demand rather than at the initial load. This improves performance by reducing the application’s initial load time.
AngularJS does not have built-in lazy loading, but it can be implemented using third-party libraries like ocLazyLoad.
1️⃣ Why Use Lazy Loading?
🔹 Reduces initial load time: Only loads necessary modules.
🔹 Improves performance: Large applications load faster.
🔹 Better resource utilization: Only loads components when needed.
2️⃣ Installing ocLazyLoad
To enable lazy loading, first install ocLazyLoad via npm or include it in your project:
<script src="https://cdnjs.cloudflare.com/ajax/libs/oclazyload/1.1.0/ocLazyLoad.min.js"></script>
Or install via npm:
npm install oclazyload --save
3️⃣ Configuring ocLazyLoad
in AngularJS
First, add oc.lazyLoad
as a dependency in your main module:
var app = angular.module('MyApp', ['ngRoute', 'oc.lazyLoad']);
4️⃣ Lazy Loading a Module with $ocLazyLoad
Example: Loading a Dashboard Module Dynamically
app.config(function($routeProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: 'dashboard.html',
controller: 'DashboardCtrl',
resolve: {
loadModule: function($ocLazyLoad) {
return $ocLazyLoad.load('dashboardModule.js'); // Loads the module when route is accessed
}
}
});
});
5️⃣ Defining the Lazy Loaded Module
Create a separate file (dashboardModule.js
) with the module and controller:
angular.module('DashboardModule', [])
.controller('DashboardCtrl', function($scope) {
$scope.message = "Welcome to the Dashboard!";
});
6️⃣ Dynamically Registering the Module
Since AngularJS does not allow dynamic module registration, we manually register the module after loading:
app.run(function($rootScope, $ocLazyLoad) {
$rootScope.$on('$routeChangeStart', function(event, next) {
if (next.resolve && next.resolve.loadModule) {
$ocLazyLoad.load(next.resolve.loadModule);
}
});
});
7️⃣ Lazy Loading Controllers, Services, and Directives
You can load not just modules, but also individual components dynamically.
Lazy Loading a Controller
.when('/settings', {
templateUrl: 'settings.html',
controller: 'SettingsCtrl',
resolve: {
loadCtrl: function($ocLazyLoad) {
return $ocLazyLoad.load('settingsController.js');
}
}
});
Summary
- Use
ocLazyLoad
to enable lazy loading. - Load modules dynamically in route
resolve
. - Register modules manually if needed.
- Lazy load controllers, services, and directives for better performance.