Lazy loading AngularJS modules with RequireJS

前端 未结 3 391
再見小時候
再見小時候 2020-11-30 07:22

Thanks to the great article from Dan Wahlin, I managed to implement lazy loading of Angular\'s controllers and services. However, there does not seem to be a clean way to l

相关标签:
3条回答
  • 2020-11-30 08:10

    I finalized my own implementation called angularAMD and here is the sample site that uses it:

    http://marcoslin.github.io/angularAMD/

    It handles config functions and out of order module definitions.

    Hopefully this can help other looking for something to help them with RequireJS and AngularJS integration.

    0 讨论(0)
  • 2020-11-30 08:12

    It looks like the Node.js module ocLazyLoad defines a way of doing this lazy-loading, though I'm not sure how it fares, performance-wise, compared to the methods in the other answers or hard-coding the dependencies. Any info on this would be appreciated. One interesting thing is that the other answers need RequireJS to operate, while ocLazyLoad doesn't.

    It looks like ocLazyLoad defines another provider that injects the dependency after the containing module has already been instantiated. It seems to do this by essentially replicating some low-level Angular behavior, like module loading and providing, hence why it looks so complicated. It looks like it adds just about every core Angular module as a dependency: $compileProvider, $q, $injector, ng, and so many more.

    0 讨论(0)
  • 2020-11-30 08:24

    Take a look at my project in GitHub: angular-require-lazy

    This project is intended to demonstrate an idea and motivate discussions. But is does what you want (check expenses-view.js, it loads ng-grid lazily).

    I am very interested in comments, ideas etc.


    (EDIT) The ng-grid Angular module is lazy loaded as follows:

    1. expenses-view.js is loaded lazily, when the /expenses route is activated
    2. expenses-view.js specifies ng-grid as a dependency, so RequireJs loads ng-grid first
    3. ng-grid is the one that calls angular.module(...)

    In order to accomplish this, I replaced (proxied actually) the real angular.module method with my own, that supports laziness. See bootstrap.js and route-config.js (the functions initLazyModules() and callRunBlocks()).

    This implementation has its drawbacks that you should be aware of:

    1. Config functions are not implemented (yet). I do not know if it is possible to lazily provide config-time dependencies.
    2. Order matters in definitions. If service A depends on B but A is defined after B in your module, DI wil fail. This is because the lazyAngular proxy executes definitions immediately, unlike real Angular that makes sure dependencies are resolved before executing the definitions.
    0 讨论(0)
提交回复
热议问题