Lazy loading components in AngularJS

There is no need to load everything at first load for an AngularJS application. It only delays initialization, increases the web application’s size and hurts performance. It would be so much simpler if you could just load components when they are used and not sooner. (FYI, a component is one of AngularJS directives/filters/services and even entire modules.)

There is a lot of talk about AngularJS and lazy-loading. There are some rumours and feature requests for Angular 2.0 to support lazy loading. At the moment there are many solutions to do this and there is no “recommended” way of doing it.

This is a simple tutorial to get your app lazy-loaded.

Clear End Goal

Load a component only when it appears on the current page.

Step 1 – Registering components after bootstrap

The main problem with loading components after the application started is that you cannot register them in the usual way (ex, app.controller) any more. As far as I know, the only way to register a component after the application starts, is to make use of the relevant provider directly. For instance:

These providers are only available during the configuration phase of the application, so you must save a reference to them during this phase. My advice is to replace the standard register function with the provider’s register function. This way, if a component is loaded before bootstrap, it will register using the standard methods, otherwise it will be registered using the providers. The component itself requires zero changes.

Step 2 – When to load components

Normally in an AngularJS application you would have a master index.html that references your entire application with all the required components. We want to avoid that and only load the component if it is actually used in the page.

For instance, we might want to lazy load AboutUs_controller.js file until the user visits the “About Us” page. First you remove its reference from index.html. Second, you load the file using your favourite script loader when the user visits the /about-us route.

We can do that by using the resolve propriety of AngularJS routes. This is not a routing tutorial for AngularJS and I assume you know what this function does. You can always refresh your memory here. Most important changes are in index.html and apps.js files.

In this resolve function, we return a promise that only gets resolved when all the lazy-loaded components are loaded and executed.

Finally

By removing components from your index.html and lazy-load them during the resolve phase of the routes, we now have a lazy-loaded AngularJS application. Depending on your application configuration, you can save quite a few bytes to bootstrap your application.

You can also view all the changes I made for Sky Watch to enable lazy-loading here.

Related posts

Comments are closed.