Travel the world

Climb the mountains

Post Page Advertisement [Top]

angularrequire.js

AngularJs Lazy loading of controller, views, services & dependency libraries.

Lazy Loading

Download example form here

When your project size increases gradually it’s not always possible to include all controllers & dependency libraries at a time. If you do so, then size of the page & loading time will increases. Alternate way is to load controllers, views & dependencies libraries on demand.

Unfortunately, Angular.js doesn’t come with built-in feature to implement lazy loading. Lazy loading is the practice of loading expensive resources on-demand.

Although there are other methods available, in our project we will discuss about require.js implementation with angular.js. We will discuss about the easiest way to implement require.js in our new/existing project.

We will use angular routing with require to achieve our goal.

Here’s how it works:

Folder structure for our application


In our index.html we will load the following.


  • We will declare require_config.js which contains config for require.js. You can load angularjs, app.js directly or with require.js. To make it more clean & simple for everyone, I have not registered module in require_config.js file.
  • The app.js file defines the application’s main module and also handles configuring routes.Notice that within the config() function an object literal is assigned to app.register (app represents the application’s module). The object literal contains properties that can be used to dynamically register a controller and other AngularJS objects that are downloaded on-the-fly.
  • Application routes are defined using the routeResolver provider’s resolveController() function which accepts the base name to use to lookup views and controllers as mentioned earlier based on conventions. Here you need provide the path for the controller file.

In your controller file.


  • Controllers in the application rely on RequireJS to access the object representing the application’s module and then access the register property shown earlier to register a controller script with AngularJS. This type of registration is required since using the standard angular.module(“ModuleName”).controller() code won’t work properly with dynamically loaded controller scripts (at least at the current time). An example of a controller named customersCtrl.js is shown next.
  • Notice that it uses RequireJS’s define() function to get to the app object and then uses it to register the controller. The app.register.controller() function points to AngularJS’s $controllerProvider.register() function behind the scenes as shown earlier with app.js. All of the controllers in the application follow this pattern.

What about Directives, Filters and other Types?

You can use the same method as controller to register your directive, filters, factory & services.


No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib