1.AngularJS Load on Demand
ANGULARJS main application Development Spa (single Page application) project, so in small projects, services, filters, and controllers are loaded in index.html. Google gives the ANGULARJS official Angular-seed and Angular-phonecat are the same.
For a complex, large-scale project, if all the content starts to load, the performance impact on the home page is relatively large, even if the static JavaScript files using CDN, the performance has a great impact. All need to introduce an on-demand loading mechanism, while in the angular1.x version, Oclazyload is a good button loading solution.
Features of the 2.ocLazyLoad
Oclazyload:your Solution for lazy loading with Angular 1.x
To get started, you can refer to: Oclazyload QuickStart, the code is very simple:
- 1. Introduction of Oclazyload file, can be used
npm
and bower
to install
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script><script src="libs/angular-ui-router/angular-ui-router.js"></script><script src="libs/ocLazyLoad/ocLazyLoad.js"></script>
- 2. Inject Oc.lazyload module
var myApp = angular.module("MyApp", ["oc.lazyLoad"]);
- 3. Load a specified module in the controller
myApp.controller("MyCtrl", function($ocLazyLoad) { $ocLazyLoad.load(‘testModule.js‘);});
In the actual project, both the service and controller files are loaded through oclazyload and are loaded in resolve. The code examples are as follows:
.state(‘detail‘,{ url:"/detail/:bookId", templateUrl:"/templates/detail.html", controller:"DetailController", controllerAs:‘ctrl‘, resolve:{ load:[‘$ocLazyLoad‘,function($ocLazyLoad){ return $ocLazyLoad.load([ ‘services/dataService.js‘ ]); }], currentBook:[‘$ocLazyLoad‘,‘$stateParams‘,‘$injector‘,function($ocLazyLoad,$stateParams,$injector){ var bookId=$stateParams.bookId; return $ocLazyLoad.load(‘services/booksService.js‘).then(function(){ return $injector.get(‘booksService‘).getBookById(bookId);; }); }] } })
3.resolve Properties
Resolve is an object (Key-value) in the state configuration parameter, and each value is a function that can rely on injection, and returns a promise (or, of course, a value, resloved defer).
Load service in 4.resolve
The services are loaded in resolve, but the requests are asynchronous and the order returned is not in order. In Currentbook, you need to call the Getbookbyid () method inside the Booksservice. This time, although dataservice.js is already loaded in load, it is not possible to use the Getbookbyid () method in Currentbook, so booksservice.js must be reloaded in the Currentbook object. The Get () method in $injector is required at this time. $injector
5. Book List and detail page demo
Code Address: Https://github.com/liminjun/ocLazyLoad-resolve-demo
6. Reference URL
Angular application How to implement on-demand loading
Oclazyload
Resolve Property in Ui-router
Comprehensive example
Http://www.cnblogs.com/xing901022/p/4941166.html
Using Oclazyload and resolve in Ui-router