[AngularJS] 5 simple ways to speed up your AngularJS application
2015-11-02 02:50
573 查看
Nowdays, Single page apps are becoming increasingly popular among the fornt-end developers. It is the time to say goodbye with refreshing the whole page due to clicking on a single link. It helps to speed up out web application and improve our use experience. Today we'd talk about how to speed up your AngularJS application. This article is based on AngularJS 1.3.x version.
[b]1. Disabling the debug info[/b]
When you use directive, Angular adds some additional debug information to the DOM.
Javascript:
HTML:
Once compiled, we get something like this:
This debug info is super useful when you debuggin because the tools like Protractor and Batarang which can rely on this information. However, great things always come with cost. When our project comes to production, those information is useless to users. And additional properties and classes that are added to the DOM also come with a performance cost depending on how much is stored on the scope and DOM operations are expensive anyway.
AngularJS 1.3 enables us to switch those debug information, what you need to do to disable the debug info:
To enable it again, you can do in console:
[b]2. Use $applyAsync[/b]
Configure $http service to combine processing of multiple http responses received at around the same time via $rootScope.$applyAsync. This can result in significant performance improvement for bigger applications that make many HTTP requests concurrently (common during application bootstrap) [1].
Sinlge $http request triggers $digest() which can help to update application model and DOM. If you have many $http requests triggered almost at the same time and each request will run $digest() which cost a lot.
The idea to use $applyAsync is to compile multiple $http requets into one $digest. We show how to use this here:
[b]3. Using one time binding[/b]
AngularJS comes up with two way binding which is cool because you don't need to set up any event listen, it helps you to update the model automaticlly. But, as we said, great thing comes with cost. In order to make databinding possible, Angular uses $watch APIs to observe model mutations on the scope. Imaging if there is too many watcher, your application become heavy and slow. This is why we need one-time binding. One-time expressions will stop recalculating once they are stable, which happens after the first digest.
You can see the demo here: http://jsbin.com/dijeno/9/edit?html,css,js,output
The way to use one time binding is quite simple, from our first simple of AppController, we know that everytime appCtrl.message changes, {{appCtrl.message}} will also change. So if we apply the one-time expression to our example above, we change this:
[b]4. Using lazy loading[/b]
Lazy loading is very useful when you have a large application which needs to load hundred files. And among those hundred files, there is only 10% files whcih are needed to bootstrap your applcation and the other 90% are only useful in the running time. So, in order to speed up, you don't want those 90% files loaded when the boostrap time. That is the place where lazy loading comes in to handy.
There are many ways to do lazy loading, for example RequireJS, the one which I often use is called ocLazyLoad. It is quite easy to use with AngularJS.
What you need to do first is install ocLazyLoad:
Then inject into the application dependency:
Javascript: When you click on the AppCtrl, we want to load everything related to the store module.
[b]5. Resolve data beforehand[/b]
Let see two parts of code first, then talk about why resolve is good.
Controller Way:
Route Resolve:
For controller activate:
Views load right away
The Service code executes after the controller code
Animation can be shown during the view transition
For route resolve
The code executes before the route via a promise
Resolve makes the new view wait for the route to resolve
Animation can be shown before the resolve and through the view transition
Resolve happens before your controller will instantiate, and your template will load and everything will set up. It gives users a felling that they can wait less time to get the interface updated, because all the data are already resolved (parpared) for interface to use.
[b]1. Disabling the debug info[/b]
When you use directive, Angular adds some additional debug information to the DOM.
Javascript:
app.controller('AppController', function () { this.appCtrl = this; appCtrl.message = "Hello World!"; });
HTML:
<p>{{appCtrl.message}}</p>
Once compiled, we get something like this:
<p class="ng-binding">Hello World!</p>
This debug info is super useful when you debuggin because the tools like Protractor and Batarang which can rely on this information. However, great things always come with cost. When our project comes to production, those information is useless to users. And additional properties and classes that are added to the DOM also come with a performance cost depending on how much is stored on the scope and DOM operations are expensive anyway.
AngularJS 1.3 enables us to switch those debug information, what you need to do to disable the debug info:
app.config(function( $compileProvider ) { $compileProvider.debugInfoEnabled(false); });
To enable it again, you can do in console:
angular.reloadWithDebugInfo();
[b]2. Use $applyAsync[/b]
Configure $http service to combine processing of multiple http responses received at around the same time via $rootScope.$applyAsync. This can result in significant performance improvement for bigger applications that make many HTTP requests concurrently (common during application bootstrap) [1].
Sinlge $http request triggers $digest() which can help to update application model and DOM. If you have many $http requests triggered almost at the same time and each request will run $digest() which cost a lot.
The idea to use $applyAsync is to compile multiple $http requets into one $digest. We show how to use this here:
app.config(function($httpProvider) { $httpProvider.useApplyAsync(true); });
[b]3. Using one time binding[/b]
AngularJS comes up with two way binding which is cool because you don't need to set up any event listen, it helps you to update the model automaticlly. But, as we said, great thing comes with cost. In order to make databinding possible, Angular uses $watch APIs to observe model mutations on the scope. Imaging if there is too many watcher, your application become heavy and slow. This is why we need one-time binding. One-time expressions will stop recalculating once they are stable, which happens after the first digest.
You can see the demo here: http://jsbin.com/dijeno/9/edit?html,css,js,output
The way to use one time binding is quite simple, from our first simple of AppController, we know that everytime appCtrl.message changes, {{appCtrl.message}} will also change. So if we apply the one-time expression to our example above, we change this:
<p>{{::appCtrl.message}}</p>
[b]4. Using lazy loading[/b]
Lazy loading is very useful when you have a large application which needs to load hundred files. And among those hundred files, there is only 10% files whcih are needed to bootstrap your applcation and the other 90% are only useful in the running time. So, in order to speed up, you don't want those 90% files loaded when the boostrap time. That is the place where lazy loading comes in to handy.
There are many ways to do lazy loading, for example RequireJS, the one which I often use is called ocLazyLoad. It is quite easy to use with AngularJS.
What you need to do first is install ocLazyLoad:
bower install oclazyload
Then inject into the application dependency:
var app = angular.module("demo", ["oc.lazyLoad"])
Javascript: When you click on the AppCtrl, we want to load everything related to the store module.
app.controller("AppCtrl", function($ocLazyLoad) { var app = this; app.click = function() { $ocLazyLoad.load({ name: "store", files: [ "app/store/store.js", "app/store/store.tpl.html", "app/css/store.css" ] }) } })
[b]5. Resolve data beforehand[/b]
Let see two parts of code first, then talk about why resolve is good.
Controller Way:
function MainCtrl(SomeService) { var mainCtrl= this; // unresolved mainCtrl.something; // resolved asynchronously SomeService.doSomething().then(function(response) { mainCtrl.something = response; }); } angular.module('app', []) .controller('MainCtrl', MainCtrl);
Route Resolve:
// config with resolve pointing to relevant controller function config ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs: 'main', resolve: MainCtrl.resolve }); } // controller as usual function MainCtrl (SomeService) { // resolved! this.something = SomeService.something; } // create the resolved property MainCtrl.resolve = { doSomething: function (SomeService) { return SomeService.doSomething(); } }; angular .module('app') .controller('MainCtrl', MainCtrl) .config(config);
For controller activate:
Views load right away
The Service code executes after the controller code
Animation can be shown during the view transition
For route resolve
The code executes before the route via a promise
Resolve makes the new view wait for the route to resolve
Animation can be shown before the resolve and through the view transition
Resolve happens before your controller will instantiate, and your template will load and everything will set up. It gives users a felling that they can wait less time to get the interface updated, because all the data are already resolved (parpared) for interface to use.
相关文章推荐
- Android之解析XML文件
- Objective-C之@class的使用
- cocos2d-x带有自定义button响应事件的messagebox
- android studio之argument for @notnull parameter 'name'
- Android 解决方法数超上限遇到的问题
- 12、Swift语言中类和结构体的应用
- AndroidListView工作理完全解析 带你从源码的角度彻底理解
- AndroidListView工作理完全解析 带你从源码的角度彻底理解
- Android动画
- android添加触摸事件
- Android 开发中,有哪些坑需要注意?
- SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoade
- nagios
- Android开发涉及有点概念&相关知识点(待写)
- hybridapp进阶篇:你需要知道的开源代码库
- ios中实现staggeringBeauty的效果(三)
- 在Android library中不能使用switch-case语句访问资源ID的原因分析及解决方案
- android sqlite应用优化(资料整理)
- android退出应用程序
- hybridapp/webapp的前端UI框架推荐