Using the Component Router In Angular 1: Lazy Loading

One of the best features of the component router in Angular 2 is support for lazy loading out the box. The component router for Angular 1 can also take advantage of this functionality. Combined with ocLazyLoad, a third party library for Angular 1, lazy loading of modules before loading routes is easy.

First, we’ll start with a simple Angular 1.5 application. The entire application including all of its components and routes load at once.

If this were a larger application, you would have more modules and components to manage. Its good practice to break up your application into smaller, more manageable modules and only load the parts of your application that are necessary upfront. Our next step is to move parts of the application into a separate module. First you’ll need to add the ocLazyLoad scripts into the <head> section of your document, and then add the module to your main application.

From there, we will change our User route to user the loader function instead of the component. The loader function must return a promise that resolves to the name of the component for the route. The ocLazyLoad loading mechanism returns a promise letting us know the module has been loaded, and then we’ll return the name of our user component.

Only the main module remains in the application. We have our user module in a separate file (user.js) that is loaded only when the user visits the User Profile link.

And that’s it, the core of the application has been loaded with other sections of the application loaded on demand. You could also use lazy loading to verify a user has access to certain parts of your application before even loading in the module, which gives you more control of what users have access to. Thanks to the component router, lazy loading modules in your application is a little bit easier.

See here for a live example on Plunker: http://plnkr.co/edit/dwdM0x?p=preview