18 Quick Tips for Improving AngularJS Performance
AngularJS is an open source JavaScript framework developed and maintained by Google. The tool provides everything you need to create and manage dynamic frontends for web applications. Its modular approach to web design and massive support community make AngularJS a popular tool among professional developers. In fact, AngularJS powers some of the web's most high traffic websites including Google and Virgin America. This guide will serve as an introduction to AngularJS and offer tips on how to improve AngularJS performance.
What is AngularJS?
AngularJS was created to simplify the complex process of building and managing JavaScript applications. Based on the Model-View-Controller, or MVC, programming structure, AngularJS is especially useful for creating single page web apps. With a JavaScript library based on standard JS and HTML, AngularJS automatically takes care of things like DOM manipulation and AJAX glue that would otherwise have to be coded by developers. The tool provides modular building blocks of JavaScript for developers to mix, match and test. AngularJS can quickly be added to any HTML page with a simple tag.
The pros and cons of AngularJS
A few features set apart AngularJS from its competition including:
- Simplified two-way data binding. AngularJS allows you to bind data to HTML using expressions, and AngularJS directives let developers extend their HTML functionality to create new constructs. Things like DOM manipulation and data binding code get condensed into simple elements that can be quickly and easily embedded in HTML templates.
- Since AngularJS was designed to be a highly versatile framework, it can be used to create almost any type of web application. If you're building a dynamic single page app, there is likely no better alternative.
- AngularJS is part of the MEAN software bundle, which also includes MongoDB, Express.js, and Node.js. Therefore, it allows you to manage both the front and backend of projects using only JavaScript. Alternatively, Ruby on Rails makes a great complimentary backend. ASP.NET and C# also pair well with AngularJS.
- Because AngularJS was built with a functionality-first mindset, it's best suited for a top-down development process. The modular nature of AngularJS makes it easy to divide the labor in large-scale projects among different teams. It also greatly simplifies the testing and debugging process. Because they prioritize using a minimal amount of code, AngularJS applications tend to be compact and easy to edit.
Nonetheless, there are some things that you should take into consideration when deciding if AngularJS is the right fit for your project.
- First and foremost, AngularJS is considered to be very opinionated, which means that it imposes structure on developers. For novice and even expert programmers, this is generally good news. AngularJS was designed to be as user-friendly as possible, so its tools are fairly intuitive. However, developers who crave more flexibility may find themselves having to "work around" the framework.
- For some projects, using AngularJS might be overkill. Lightweight frameworks such as Backbone.js may be a better option for static websites. AngularJS also isn't equipped to handle data-intensive DOM manipulation since it relies on "dirty checking" to manage DOM changes, which means that any alterations to variables trigger a DOM update. Although that's not an issue for many websites, it could cause applications like GUI editors and video games to lag.
- AngularJS also struggles to support high-traffic photo galleries, which is why Instagram wasn't built on the framework. You can work around these performance issues, but it might be better to go with an alternative like React. Otherwise, AngularJS is capable of supporting forms with high levels of user interaction; after all, it does power Gmail.
AngularJS optimization tips
AngularJS has plenty of built-in optimization tools, but performance complaints still plague the framework. If you don't have the massive infrastructure that Google has, you might need to implement some best practices to improve your AngularJS application's performance.
Whether you know you're in need of a performance boost, or if you just want to see if there is room for improvement, here are some tips for getting your AngularJS apps up to speed:
1. Keep an eye on your digest cycle
The digest cycle of your AngularJS app is a good indicator of its performance. Think of the digest cycle like a loop that checks for changes to variables being monitored. The shorter the digest cycle, the faster your application will run.
2. Limit your watchers
Speaking of which, any time you introduce data-bindings, you create more $$watchers
and $scopes
, which prolongs the digest cycle. Too many $$watchers
can cause lag, so limit their use as much as possible.
3. Use one-time binding, if possible
If you're using an older version of AngularJS, you may be able to take advantage of one-time binding. To do so, just add a double-colon before the value. If applied correctly, the value will resolve once and then disappear from the watchers list. It's important to note that the one-time binding feature, which was introduced in AngularJS 1.3, is not available in Angular 4.0.
4. Use scope.$evalAsync
If you try to manually activate the digest cycle while it's already running, you could get an error. To prevent this from happening, use scope.$evalAsync
instead of $apply
when you need to initiate the digest cycle. It queues up operations to be executed at the end of the current cycle without setting off a new one.
5. Use Chrome DevTools Profiler and Timeline
Both the DevTools Profiler and the Timeline tools can help you find performance bottlenecks to guide your optimization efforts. Read our in-depth guide on Chrome DevTools.
6. Limit DOM access
Accessing the DOM can get expensive, so keep your DOM trees small. Don't modify the DOM if you can help it, and don't set any inline styles to avoid JavaScript reflow.
7. Disable CSS class and comment directives
When creating a directive, you can designate it to be used as an element, attribute, CSS class or comments. If you don't need CSS class and comment directives, disable them for a performance boost.
8. Disable debug data
Tools like Protractor rely on the data about binding and scopes that AngularJS attaches to DOM elements. Therefore, when you're done debugging, disable the extra data so that it doesn't drag your application down.
9. Use Lodash
Lodash lets you quickly rewrite your application's logic to improve upon the built-in AngularJS methods and enhance your application's performance. If your web app doesn't use Lodash, you can rewrite the methods yourself using native JavaScript.
10. Use ng-if
or ng-switch
instead of ng-show
The directive ng-show
simply toggles the CSS display on or off for a specified element.
To remove an element from the DOM, you must use ng-if
or ng-switch
.
11. Avoid ng-repeat
when possible
Overuse of the ng-repeat
directive can drastically drive down performance. Fortunately, there are alternatives. For instance, rather than employing ng-repeat
to render a global navigation, you could make your own by using the $interpolate
provider to render your template against an object before converting it into a DOM node.
12. Use $watchCollection
When you're using $watch
, two parameters are great, but three's a crowd. Adding a third parameter forces AngularJS to run deep checking, which eats up a lot of resources. The developers were nice enough to include a work around: $watchCollection
. It behaves as a third parameter for $watch
, yet it just checks the first layer of each object's properties, so it doesn't slow things down as much.
13. Use $cacheFactory
If you need to store data that you might need to recalculate later, use the $cacheFactory
directive. It works like any other memoization method.
14. Use console.time
If you're having problems debugging, console.time
(Chrome DevTools) is an excellent tool for measuring execution times and other performance benchmarks.
15. Debounce ng-model
Debouncing inputs using the ng-model
directive can limit the digest cycle. For example, applying ng-model-options="{debounce:200}"
ensures that the digest cycle doesn't run more than once every 200 ms.
16. Use $filter
AngularJS runs DOM filters twice during each digest cycle: first to detect changes, and then to update values that have changed. To save some time, the $filter
provider allows you to preprocess data before it gets sent to the View and thus skips the DOM parsing process.
17. Tight scoping
Keep your variables scoped tightly so that the JavaScript garbage collector can free up some memory every now and then.
18. Pagination or infinite scroll
If all else fails, you can lower the number of elements that get looped over by implementing pagination or infinite scroll. AngularJS even has a directive called ngInfiniteScroll
for that purpose.
It's always more efficient to employ best practices from the beginning rather than to keep going back and making changes. Before you start coding, think carefully about how you can limit bindings, watchers and expensive directives like ng-repeat
. Consult the official AngularJS docs for troubleshooting and additional help getting started.
AngularJS performance and testing tools
You can find a number of tools dedicated to improving the testing and performance of AngularJS apps. Here are a few of the best options:
1. Protractor
Protractor comes straight from the Angular team. This software bundle allows you to run automated end-to-end testing with ease. Because Protractor is built on top of webDriverJS and Selenium server, it boasts all of their features, which means you can use the Selenium grid feature to simultaneously run tests in multiple browsers. You can write your own test suites using Jasmine or Mocha.
2. WebDriverIO
As an implementation of W3C webDriver API, WebDriverIO is more flexible than WebDriverJS. Its command line interface makes setting up tests easy enough for non-programmers to figure out. WebDriverIO users benefit from excellent support and an active developer community.
3. NightwatchJS
NightwatchJS is also a custom implementation of W3C webdriver API. Easy to extend and customize, this tool comes with its own testing framework and assertions mechanisms, yet it lacks the level of support that WebDriverIO and Protractor have.
4. TestingWhiz
Dynamic commands allow TestingWhiz to sync with varying server wait times to provide accurate end-to-end testing of Angular apps. The codeless scripting feature makes TestingWhiz highly popular among non-programmers.
Summary
As a final note, also considering using a CDN to speed up your AngularJS assets. This will optimize the load time for visitors around the globe thanks to smart caching.
Although there are dozens of JavaScript frameworks these days, AngularJS remains a favorite for many, so it won't be going anywhere anytime soon. To get the most out of your applications, you should make AngularJS optimization a regular habit. Fine-tuning your application's performance might allow you to provide more content while using less code, which frees up resources that could be better spent elsewhere.