Lazy Loading in AngularJS

Posted By : Himanshu Goyal | 06-Jun-2016



Intro:
In most application we will include all the file at first time in application .We include the scripts in index.html file.Which will be loaded at the begining of the application.But the oclazzyloading in angularJS module which willl helps to load the file at run time when they needed. It will helps to boost the speed of large application.you can load the any controller,service,directive ,tooster and any functionlty which is only require once in the module. 

Steps: Few Simple steps to include the module in your application

  • Include the oclazyloading script file in the application .
  • Include the depandancy in the angular module ie oc.lazyLoad
  • Now you can use it load the controller,css,external module with oc.lazzyload 

Code: Load the controller using Oclazyloading

 /*
@author:Himanshu Goyal
Independent module which you can load through lazy loading
*/
angular.module('loginModule', [{
//here you can include any service which you want to load using lazy loading 
}]).controller('loginController', ['$scope', 'dataFactory', function ($scope, apiService) {
    console.log("login controller is called");
    apiService.saveTokenHeader("SS")
    console.log(apiService.getTokenHeader());
}]);

/*
@author :Himanshu Goyal
Provide the controller at run time 
*/
var app = angular.module('tihm', ['ui.router', 'ngResource', 'UrlConfiguration', 'oc.lazyLoad']);

app.config(function ($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {

    //  $urlRouterProvider.otherwise('/login');

    $stateProvider.
    state('login', {
        url: '/login',
        templateUrl: "app-module/login/template/login.html",
        controller: "loginController as loginModule",
        resolve: {
            loginModule: ['$ocLazyLoad', function ($ocLazyLoad) {
                return $ocLazyLoad.load({
                    name: "loginModule",
                    files: ['app-module/login/controller/loginController.js']
                })
                  }]
        }
    })
})
 

Note: During the state change the first the resolve symbol will loaded and it will provide the lazy loading of the controller . If you have any dobut or query fell free and query me at  [email protected]

THANKS

About Author

Author Image
Himanshu Goyal

Himanshu is a bright Java ,Mean stack developer and have good knowledge of Hibernate, Spring,FFmepg,Neo4j JSON, Jquery, NODE.JS .His hobbies are learning new things, fitness .

Request for Proposal

Name is required

Comment is required

Sending message..