Lazy load modules and controllers in AngularJS

July 6, 2016
by Inaam Hussain

In this AngularJS tutorial, we will learn how we can add lazy loading to our Angular application. In application what we do is, include all the css and js files in the main index page. This may result in longer application load time which may eventually result in user leaving your application and hence higher bounce rate.

We can avoid the above scenario by lazy loading files, which basically means loading files on demand when required.

We will use the awesome oclazyload module to achieve this.

So let’s start with the setup and configuration.

DEMODOWNLOAD

Download ocLazyLoad.js

Quick start

Add module in application

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

Load file in any controller

   app.controller("MyCtrl", function($ocLazyLoad) {
      $ocLazyLoad.load('testModule.js');
   });

There is multiple way to load your files using $ocLazyLaod.

Configuration

You can configure the service provider $ocLazyLoadProvider in config function of application, Like see below,

   app.config([ "$ocLazyLoadProvider", function($ocLazyLoadProvider) {
       $ocLazyLoadProvider.config({
           // options
       });
   }]);

In options we can set following params,

  1. debug : boolean : true/false :- Show error in console if something goes wrong.
  2. events : boolean : true/false :- it will broadcast events when you load modules. default is false, to enable pass true. events like ( ocLazyLoad.moduleLoaded, ocLazyLoad.moduleReloaded, ocLazyLoad.componentLoaded, ocLazyLoad.fileLoaded ).
  3. Event Example
      $scope.$on('ocLazyLoad.moduleLoaded', function(e, module) {
         console.log('module name : ', module);
      });
  4. modules : Array of objects :-
  5. Modules Example
      modules: [{
        name: 'testMod1',
        files: ['js/testModule1.js']
      }]

    And when we need to load, $ocLazyLoad.load(‘testMod1’) it will load from predefined configuration.

ocLazyLoad with router

ocLazyLoad works perfectly with routers like UI-Router. It return a promise, and uses resolve property to make sure that files or component are loaded before the view is resolved.
Lets start with UI router to see how resolve works,

app/app.js
//Config For ocLazyLoading
$ocLazyLoadProvider.config({
    'debug': true, // For debugging 'true/false'
    'events': true, // For Event 'true/false'
    'modules': [{ // Set modules initially
        name : 'state1', // State1 module
        files: ['app/components/state1/state1Module.js']
    },{
        name : 'state2', // State2 module
        files: ['app/components/state2/state2Module.js']
    }]
});

First we will configure for ocLazyLoad, just set debug to true for debugging purpose. Also set events to true/false accordingly to fire events.
And then add resolve in router’s code. See below,

app/app.js
//Config/states of UI Router
$stateProvider
    .state('state1', {
        url: "/state1",
        views : {
            "" : {
                templateUrl:"app/components/state1/state1View.html"
            }
        },
        resolve: {
            loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load('state1'); // Resolve promise and load before view
            }]
        }
    })
    .state('state2', {
        url: "/state2",
        views : {
            "" : {
                templateUrl:"app/components/state2/state2View.html"
            }
        },
        resolve: {
            loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load('state2'); // Resolve promise and load before view
            }]
        }
    });

So in the state we have added promises to first load modules and then view. Basically, inject $ocLazyLoad and use that to load files or modules accordingly. After resolving promise it will load views.

Here are some screenshot that show loaded files in console for both the states,
For state1,

lazy load state1

lazy load state1

and when we click on state2,

lazy load state2

lazy load state2

see below full working app module’s code,

app/app.js
var app = angular.module('lazyLoadApp', ['ui.router', 'oc.lazyLoad']);
app.config(['$ocLazyLoadProvider', '$stateProvider', '$urlRouterProvider' , function($ocLazyLoadProvider, $stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/state1");
    //Config For ocLazyLoading
    $ocLazyLoadProvider.config({
        'debug': true, // For debugging 'true/false'
        'events': true, // For Event 'true/false'
        'modules': [{ // Set modules initially
            name : 'state1', // State1 module
            files: ['app/components/state1/state1Module.js']
        },{
            name : 'state2', // State2 module
            files: ['app/components/state2/state2Module.js']
        }]
    });
        //Config/states of UI Router
    $stateProvider
    .state('state1', {
        url: "/state1",
        views : {
            "" : {
                templateUrl:"app/components/state1/state1View.html"
            }
        },
        resolve: {
            loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load('state1'); // Resolve promise and load before view
            }]
        }
    })
    .state('state2', {
        url: "/state2",
        views : {
            "" : {
                templateUrl:"app/components/state2/state2View.html"
            }
        },
        resolve: {
            loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load('state2'); // Resolve promise and load before view
            }]
        }
    });
}]);

Conclusion

Lazy loading is a very important factor while creating single page applications. In this AngularJS tutorial, we learnt how we can achieve lazy loading in AngularJs applications using the module ocLazyLoad. Using this we can easily distribute files based on state routes. This will also improve the performance of our apps and load apps quicker initially.

For more info please visit following Link : ocLazyLoad

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

3 comments

  1. |

    Hi.
    I used above oc.lazyLoad concept in my project, everything is working good from html side but i am facing problem from controllers side in browser networks the controller is downloaded but it is not loading ,
    my dynamic values are not loading from controllers ….
    so pl z tell me how to solve this issue

    Thank you
    sasi y

    • |

      Hi Sasi,
      just make sure all the related files that you have linked properly and controller specified its proper location. it has to work. or else give me your code highlight on my mail id. will look into it.
      Thanks.

  2. |

    Thanks for this really nice tutorial !

    Unfortunatelly I’ve a problem, my .js files are well dynamically loading but not my html file… I’m note using stateProvider but routeProvider. Do you have any idea why ?

Leave a Comment