Inject module dynamically, only if required

I have been trying to mix requirejs+Angular for some time now. I published a little project in Github (angular-require-lazy) with my effort so far, since the scope is too large for inline code or fiddles. The project demonstrates the following points:

  • AngularJS modules are lazy loaded.
  • Directives can be lazy loaded too.
  • There is a “module” discovery and metadata mechanism (see my other pet project: require-lazy)
  • The application is split into bundles automatically (i.e. building with r.js works)

How is it done:

  • The providers (e.g. $controllerProvider, $compileProvider) are captured from a config function (technique I first saw in angularjs-requirejs-lazy-controllers).
  • After bootstraping, angular is replaced by our own wrapper that can handle lazy loaded modules.
  • The injector is captured and provided as a promise.
  • AMD modules can be converted to Angular modules.

This implementation satisfies your needs: it can lazy-load Angular modules (at least the ng-grid I am using), is definitely hackish 🙂 and does not modify external libraries.

Comments/opinions are more than welcome.


(EDIT) The differentiation of this solution from others is that it does not do dynamic require() calls, thus can be built with r.js (and my require-lazy project). Other than that the ideas are more or less convergent across the various solutions.

Good luck to all!

Leave a Comment