What Is Lazy Loading?
Single page application, as you can see from its name - is built with one single page. In this single page javascript loads (when needed) various views. Each view may have its won modules, components, and other javascript logic inside them. Since it may happen that site user will not access some views at all - it is good practice to avoid load then every time the app accessed, istead - the ideal tactic is to load those javascript parts only when this specific view was called. But is there some way to do it in angular1?
The Answer is Yes
Actually there is a way to implement lazy loading with angularjs, for example by using ocLazyLoad angular module. You can read here how to load entire module or only some directive or service or how to load some state from a script!
Experiment
As usual lets show how to use lazy loading on some of our old good projects - the angular phonecat.
Lets start with download or clone the project to some local directory.
git clone https://github.com/angular/angular-phonecat.git
After installing dependencies (npm i) lets register the ocLazyLoad module to bower.json:
bower i oclazyload -D
After install and place reference on index.html file, we must register lazy load module in root application module:
'use strict';
// Define the `phonecatApp` module
angular.module('phonecatApp', [
'ngAnimate',
'ngRoute',
'core',
'phoneDetail',
'phoneList',
'oc.lazyLoad'
]);
Create About Page
For testing lazy load feature lets create "about" module which will contain "component","config","module" and "template" files
we will rester only "config" and "module" references on the index.htmlLets add about module to our root "phonecatApp" module:
angular.module('phonecatApp', [
'ngAnimate',
'ngRoute',
'core',
'phoneDetail',
'phoneList',
'oc.lazyLoad',
'about'
]);
We didn't put the reference to about.component fie on the index.html on the purpose.The "component" file will load with lazy load module after user will access "about" route.
angular.module('about').
config(['$locationProvider', '$routeProvider',
function config($locationProvider, $routeProvider) {
$routeProvider.
when('/about', {
template: '<about-comp></about-comp>',
resolve: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load([{
files: ['about/about.component.js']
}])
}]
});
}
]);
Lets try to navigate to /about urlWow! Now you can see the about component is loaded!
Thanks for reading
No comments:
Post a Comment