Lazy loading modules using AngularJS routing

Loading

Lazy loading in AngularJS helps improve performance by loading modules only when needed rather than at the start. This is especially useful for large applications with multiple views.


1. Why Use Lazy Loading?

  • Faster initial load time – The app loads only the essential parts first.
  • Optimized resource usage – Loads modules only when required.
  • Better performance – Reduces unnecessary memory consumption.

2. How Lazy Loading Works in AngularJS?

AngularJS doesn’t have built-in support for lazy loading, but you can achieve it using:

  1. $ocLazyLoad Module – Loads modules on demand.
  2. Dynamic Dependency Injection – Loads controllers and services dynamically.

3. Setting Up Lazy Loading with $ocLazyLoad

Step 1: Include AngularJS and Required Libraries

Include AngularJS, angular-route.js, and ocLazyLoad.js.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/oclazyload/1.1.0/ocLazyLoad.min.js"></script>

Step 2: Create AngularJS App and Configure Routes

Define the main app module with ngRoute and oc.lazyLoad.

var app = angular.module("myApp", ["ngRoute", "oc.lazyLoad"]);

app.config(["$routeProvider", "$ocLazyLoadProvider", function($routeProvider, $ocLazyLoadProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "HomeController"
})
.when("/dashboard", {
templateUrl: "dashboard.html",
controller: "DashboardController",
resolve: {
load: function($ocLazyLoad) {
return $ocLazyLoad.load("dashboard.module.js"); // Lazy Load Module
}
}
})
.otherwise({
redirectTo: "/"
});
}]);

Key Points

  • The resolve property ensures that the dashboard.module.js file is loaded before the route is accessed.
  • If the module isn’t loaded, the route won’t proceed.

Step 3: Create Modules Dynamically

Create the dashboard.module.js file outside the main script.

dashboard.module.js

var dashboardModule = angular.module("dashboardModule", []);

dashboardModule.controller("DashboardController", function($scope) {
$scope.message = "Welcome to the Dashboard!";
});

Explanation

  • This file defines a separate module (dashboardModule).
  • The module contains the DashboardController, which will be used when /dashboard is loaded.

Step 4: Update the Main App to Recognize Lazy-Loaded Modules

Modify the app.js to register the lazy-loaded module dynamically.

app.run(["$rootScope", "$ocLazyLoad", function($rootScope, $ocLazyLoad) {
$rootScope.$on("$routeChangeSuccess", function(event, current) {
if (current.$$route && current.$$route.resolve) {
var moduleName = current.$$route.resolve.load;
moduleName.then(function(module) {
$ocLazyLoad.inject(module); // Inject loaded module dynamically
});
}
});
}]);

What Happens Here?

  • $routeChangeSuccess checks if the new route requires a module.
  • If so, the module is loaded and injected dynamically using $ocLazyLoad.inject().

Step 5: Create Views (HTML Templates)

home.html

<h2>Home Page</h2>
<p>Welcome to the main page.</p>

dashboard.html

<h2>Dashboard</h2>
<p>{{ message }}</p>

Step 6: Test the Lazy Loading

  1. Open the browser console (F12Network tab).
  2. Visit http://localhost/#!/.
    • Only app.js and home.html load.
  3. Navigate to http://localhost/#!/dashboard.
    • Now, dashboard.module.js is loaded only when needed.

7. Advanced Enhancements

1. Lazy Load Multiple Modules Together

If you want to load multiple modules, update the resolve function:

resolve: {
load: function($ocLazyLoad) {
return $ocLazyLoad.load([
"dashboard.module.js",
"reports.module.js"
]);
}
}

2. Handle Errors Gracefully

Wrap ocLazyLoad.load() in a promise with error handling:

resolve: {
load: function($ocLazyLoad, $q) {
var deferred = $q.defer();
$ocLazyLoad.load("dashboard.module.js").then(
function() { deferred.resolve(); },
function() { deferred.reject("Failed to load module"); }
);
return deferred.promise;
}
}

3. Use Asynchronous Module Loading

Load modules asynchronously using the require() function:

resolve: {
load: function($ocLazyLoad, $q) {
var deferred = $q.defer();
require(["dashboard.module"], function(module) {
$ocLazyLoad.inject(module);
deferred.resolve();
});
return deferred.promise;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *