Lazy / Partial Load Modules and Controllers in AngularJS Example

A complex application built using AngularJS takes a lot of time to load due to a large number of view controllers and other modules. As AngularJS acts as a web application we need to load all resources on page load. But we can adopt a new approach to load only required resources like controllers which…

By.

•

min read

A complex application built using AngularJS takes a lot of time to load due to a large number of view controllers and other modules. As AngularJS acts as a web application we need to load all resources on page load. But we can adopt a new approach to load only required resources like controllers which we need for that particular view. This is called Lazy Loading where we load what we need.

So Let’s get started to create an example application…

Here we will use oclazyload to achieve this

 

Step 1) Include ocLazyLoad.min.js in index.html root page of our application.

<script src="assets/js/lib/angular/ocLazyLoad.min.js"></script>

 

Step 2) Inject dependency for ocLazyLoad in app.module.js.

angular.module('app', ['ngRoute','oc.lazyLoad']);

 

Step 3) Create app.config.js module to define the setting for the ocLazyLoad module.

angular.module('app').config([ "$ocLazyLoadProvider", function($ocLazyLoadProvider) {
		$ocLazyLoadProvider.config({
		    'debug': true, // For debugging 'true/false'
		    'events': true, // For Event 'true/false'
		    'modules': [{ // Set modules initially
		        name : 'page1Ctrl', // State1 module
		        files: ['app/components/controller/page1Controller.js']
		    },{
		        name : 'page2Ctrl', // State2 module
		        files: ['app/components/controller/page2Controller.js']
		    },{
		        name : 'page3Ctrl', // State2 module
		        files: ['app/components/controller/page3Controller.js']
		    }]
		});
   }]);

 

Step 4) Now in app.route.js file we use resolve service to load controller or modules realtime using ocLazyLoad method. When a route is called. After successful resolve of a module, our controller will load and initialize then route success event will be fired.

For example, we need to call page 2

...
...

     .when('/page2', {
         templateUrl: 'app/components/view/page2View.html',
         title: 'page2',
         controller: 'page2Controller',
         resolve: {
            LazyLoadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
                            return $ocLazyLoad.load('page2Ctrl'); // Resolve promise and load before view 
            }]
         },
     })

...
...

 

In resolve block, we will load page2Ctrl which we defined in config settings. This will load our controller before the route change start event.

See working demo here.

Find the complete code in GitHub here.

Leave a Reply

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