Lazy load modules and controllers in AngularJS

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 ways 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 ).
Event Example
  $scope.$on('ocLazyLoad.moduleLoaded', function(e, module) {
     console.log('module name : ', module);
  });
  1. modules : Array of objects :-
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 purposes. Also, set events to true/false accordingly to fire events.

And then add resolve in the 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.

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

Facebook
Twitter
LinkedIn
Pinterest

Related posts