Lazy / Partial Load Modules and Controllers in AngularJS Example

A complex application built using AngularJS takes a lot of time to load due to a large number of view controllers and other modules. As AngularJS acts as a web application we need to load all resources on page load. But we can adopt a new approach to load only required resources like controllers which we need for that particular view. This is called Lazy Loading where we load what we need.

So Let’s get started to create an example application…

Here we will use oclazyload to achieve this

 

Step 1) Include ocLazyLoad.min.js in index.html root page of our application.

 

Step 2) Inject dependency for ocLazyLoad in app.module.js.

 

Step 3) Create app.config.js module to define the setting for the ocLazyLoad module.

 

Step 4) Now in app.route.js file we use resolve service to load controller or modules realtime using ocLazyLoad method. When a route is called. After successful resolve of a module, our controller will load and initialize then route success event will be fired.

For example, we need to call page 2

 

In resolve block, we will load page2Ctrl which we defined in config settings. This will load our controller before the route change start event.

See working demo here.

Find the complete code in GitHub here.

Leave a Reply

Your email address will not be published. Required fields are marked *