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 tried this - and while the controller loads properly (as does the file with the service), the controller can't seem to find the service it depends on. Angular throws an "unknown provider" error.

    ReplyDelete
  10. This is useful information.. Awesome I am impressing Thanks..


    Hospital Management System

    ReplyDelete
  11. Relationship Problems LoveFebruary 7, 2015 at 11:31 AM

    Thank you I love it!

    ReplyDelete
  12. Chandi Homa BenefitsFebruary 12, 2015 at 10:43 AM

    This is really informative article.

    ReplyDelete
  13. Very happy with your post. Thank you very much.

    ReplyDelete
  14. Ganapathi Homam MantraFebruary 14, 2015 at 4:00 PM

    Excellent experience.

    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.

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.

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…