Skip to main content

Lazy loading AngularJS components using Providers

I've been working on an Angular project for sometime now and I usually run across issues when building the application. In most of the example applications that I've seen, all application script files are loaded upfront i.e. all JavaScript files are loaded when the user accesses application. I get annoyed by this approach; why should all the components be loaded upfront when the probability of user accessing the entire application is very less. How does one architect a multi-page application using Angular? What would be the size of the application after minifying all the JavaScript files. Most importantly how does one load the components lazily. I've used RequireJS in my previous projects and it allows you to load components on demand; the idea is to load components based on the selected route. I've tried a similar approach with Angular using 'resolve' property in the $routeProvider.

The 'resolve' property in Angular can be used to resolve services but essentially it's a promise object that gets resolved. In my previous post, I've explained how the resolve property is used to invoke a route only after resolving a $http service. Similarly, you can load the controller and service components (JavaScript files) before invoking the route. In this example, I've used RequireJS to load the controller and service components:


In the above code snippet, files 'components/login/controllers/loginController' and 'components/login/services/loginService' are loaded using RequireJS. Once these files are loaded, the $rootScope.$apply function is called and the promise object is resolved in the callback handler. Although this seemed like a direct approach to resolving dependencies, Angular throws an error when you access the route. It throws 'function got undefined' error. The reason to this is, when Angular initializes or bootstraps the application, functions - controller, service etc,. are available on the module instance. Here, we are lazy loading the components and the functions are not available at a later point; therefore we must use the various provider functions and register these components. The providers are available only in the config method and hence we will have to store a reference of these providers in the config function when the application is initialized:

Here a reference to the $controllerProvider.register and $provide.service are stored in the 'app.components' object. Now when you create components, these reference variables should be used. For example, to create a 'loginController' component, the function signature would be:

app.components.controller('loginController');

At run-time the components are registered by Angular using the various provider services. Next step in refining this example is to use modules in r.js (RequireJS optimizer) to create single JavaScript files that define all the dependencies for the page.

Take a look at this git repo which contains two pages and components are loaded on demand - https://github.com/sagar-ganatra/angular-require-resolve/

Comments

  1. I would refactor the require([...]) call to a service and return a promise for the dependencies list. Doing that you will be able to catch failures - when a dependency cannot be loaded. In your example, if a dependency cannot be loaded the promise will remain in a pending state.

    ReplyDelete
  2. Thank you for this. It's the first lazy-load solution simple enough for me to understand. I'm only a few months into Angular but already my app has several pages and I've been hoping for a solution like this one (actually I was hoping Angular 2.0 would include it). I have no experience with require.js though, on the 2nd visit to a page, does it *reload* the services/controllers in your solution?

    ReplyDelete
  3. I think RequireJS understands that the given files have already been loaded and hence it will not load it again.

    ReplyDelete
  4. I'm kinda doubting how much lazy-loading would help - in fact, unless the application is absolutely gigantic and huge, it's actually slower to do lazy-loading.


    Why? Because normally a webapp is concatenated and minifyed (including templates) into one file, lets call it application.js.


    This means that it only takes one http request to fetch everything. Http requests are expensive, especially on mobile devices.


    Further, using AppCache makes it even better to load everything: the whole thing is cached in the browser anyway! Lazy loading therefore doesn't make much sense, imho.


    What am I missing?


    concatenation+minfication + appCache = awesome.


    Cheers from Copenhagen

    ReplyDelete
  5. Agree on all points. I really care about initial load time, http requests are processed in parallel per domain (I think it's four on Chrome). All code minified into one single file is ideal and works for most of the applications. I care about exploring scenarios where the user wouldn't visit all pages or the user may not be allowed to see some part of the application. It's always a debate b/w one http request which would take a few seconds to complete vs fast initial load and then lazy loading other parts on demand. These requests are cached anyway and hence reload of the JS files is obliterated.

    ReplyDelete
  6. Hi Sagar, thanks for your reply.

    Good points about initial loading time, as well as 'hiding' some templates/code.

    Great stuff

    ReplyDelete
  7. I would say that these comments talk about the pros and cons of this approach. Thank you!

    ReplyDelete
  8. I hope you don't mind. I forked your project and modified it a little. Adding a service to make it DRY. Here is the code, //github.com/pgarciacamou/angular-require-resolve/blob/master/src/app.js

    ReplyDelete
  9. I like your blog because I’m also in the process of studying java and python. I gather information and useful homework tips from all data sources. Unfortunately, I don’t come by college assignments very easily so I have to seek the assistance edit my essay

    ReplyDelete
  10. Best Indian WordPress Developers who are not only skilled in their technology but also keeps their promise to create a robust code for your solutions and save your money! The
    current scenarios of technology have raised the status of web development in India.

    ReplyDelete
  11. As iPad and iPhone are dominating in smartphone market; it is strategically important to make your application compatible with iOS. Indian App Developer is prominent company which provides iPhone app development India with innovative, interactive and user-friendly services in sync with your business requirement. Our highly skilled team and efficiency to develop IOS Apps that helps businesses gain their visions faster and better. Our cost-effective mobile solutions help us to serve our small & mid-sized companies and brands.

    ReplyDelete
  12. Healthcare has taken a u-turn in the last decade. Such technology advancement has made a smooth and interactive way amongst patients and doctors. Technology also plays a crucial role in healthcare app advancement. The industry has introduced two of its most great innovations. They are Virtual Reality and Wearables. The presence of Virtual Reality in healthcare making life easier for patients and specialists. Due to its flawlessness, they can safely rely on these gadgets. Virtual Reality in healthcare services offers large open doors for various organizations.

    ReplyDelete
  13. Dream11 is one of the most popular and trending fantasy app in the Indian subcontinent. It has emerged to become one of the biggest names in the fantasy sports genre of mobile applications. This application is popular because it allows the participants to win some quick money. If the participants have the right knowledge and skills, they can win a significant amount of money from each game they play. Are you wondering that how to make app like Dream11? However, you must understand that it is not an easy task to start a fantasy app development project.

    ReplyDelete
  14. Hello Admin!

    Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai | Printing in Chennai , Visit Inoventic Creative Agency Today..

    ReplyDelete
  15. Surely, this post will help you find the best IDEs for your project. Still, you find any confusion and don’t want to take a risk. You can Hire PHP Developer from the best PHP web development company, who is skilled and has worked on the latest trends. He will not only help you select the best IDE tools considering your project requirements but also will give the physical form to your project.

    ReplyDelete

Post a Comment

Popular posts from this blog

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code.

What is Minification?

Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript file…

A cheat sheet of keyboard shortcuts in ColdFusion Builder

In my last post I have explained about keyboard shortcuts in ColdFusion Builder 2.0. This blog post contains a list of all shortcut keys and I have listed these keyboard shortcuts based on the categories that it falls into. Well, this post was not planned since users can easily get to know the keyboard shortcuts by navigating to the preferences (ColdFusion -> Profiles -> Keys). However, I met Joshua at Scotch on the rocks in Edinburgh and he suggested that it would be nice to have the list of keyboard shortcuts handy. So this post is for those who would like to have the list with them and refer it whenever required.


Keyboard shortcuts for inserting text:

These are the keyboard shortcuts which are used to insert some text into the editor:

CommandKeyboard shortcuts on WindowsKeyboard shortcuts on MacInsert anchor tagCTRL + T, LCMD + T, LInsert bold tagCTRL + T, BCMD + T, BInsert br tagCTRL + T, RCMD + T, RInsert cfabortCTRL + T, ACMD + T, AInsert cfdumpCTRL + T, DCMD + T, DInsert cfs…