Lazyload controllers and modules in Angular.JS

Lazyload controllers and modules in Angular.JS

  • 2016-08-20
  • 2673

In this AngularJS instructional exercise, we will figure out how we can add lazy loading to our Angular application. In application what we do is, incorporate all the css and js records in the principle file page. This may bring about longer application load time which may in the end result in client leaving your application and subsequently higher ricochet rate.

We can stay away from the above situation by sluggish stacking documents, which essentially implies stacking records on interest when required.

We will utilize the magnificent oclazyload module to accomplish this.

So we should begin with the setup and configuration.

DEMO

DOWNLOAD

Download ocLazyLoad.js

Quick start

Include 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 arrange the administration supplier $ocLazyLoadProvider in config capacity of utilization, Like see beneath,

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

In alternatives we can set after 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']
  }]

What’s more, when we have to stack, $ocLazyLoad.load(‘testMod1’) it will stack from predefined setup.

ocLazyLoad with router

ocLazyLoad works flawlessly with switches like UI-Router. It give back a promise, and utilizations resolve property to ensure that records or part are stacked before the perspective is determined.

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']
    }]
});

In the first place we will design for ocLazyLoad, simply set troubleshoot to valid for investigating reason. Additionally set occasions to true/false in like manner to flame occasions.

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 guarantees to first load modules and afterward see. Fundamentally, infuse $ocLazyLoad and utilize that to load documents or modules as needs be. In the wake of determining guarantee it will stack sees.

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

enter image description here

and when we click on state2,

enter image description here

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

Lethargic stacking is an imperative element while making single page applications. In this AngularJS instructional exercise, we learnt how we can accomplish lethargic stacking in AngularJs applications utilizing the module ocLazyLoad. Utilizing this we can without much of a stretch circulate records in view of state courses. This will likewise enhance the execution of our applications and burden applications faster at first.

Suggest

AngularJS 2.0: What to Expect and Interesting?

Visual Studio 2015: Building JavaScript Apps with AngularJs

Ionic by Example: Create Mobile Apps in HTML5

Learn Vue JS Introduction to Simple Reactive JavaScript

ASP NET Core (ASP NET 5),MVC 6,C#,Angular2 & EF Crash Course