Inject module dynamically, only if required

后端 未结 6 2043
滥情空心
滥情空心 2020-11-30 19:52

I\'m using Require.js in combination with Angular.js.

Some controllers need huge external dependencies which others don\'t need, for example, FirstController

6条回答
  •  -上瘾入骨i
    2020-11-30 20:25

    The problem with existing lazy load techniques is that they do things which I want to do by myself.

    For example, using requirejs, I would like to just call:

    require(['tinymce', function() {
       // here I would like to just have tinymce module loaded and working
    });
    

    However it doesn't work in that way. Why? As I understand, AngularJS just marks the module as 'to be loaded in the future', and if, for example, I will wait a bit, it will work - I will be able to use it. So in the function above I would like to call some function like loadPendingModules();

    In my project I created simple provider ('lazyLoad') which does exactly this thing and nothing more, so now, if I need to have some module completely loaded, I can do the following:

    myApp.controller('myController', ['$scope', 'lazyLoad', function($scope, lazyLoad) {
    
        // ........
    
        $scope.onMyButtonClicked = function() {
    
            require(['tinymce', function() {
                lazyLoad.loadModules();
    
                // and here I can work with the modules as they are completely loaded
            }]);
        };
    
        // ........
    
    });
    

    here is link to the source file (MPL license): https://github.com/lessmarkup/less-markup/blob/master/LessMarkup/UserInterface/Scripts/Providers/lazyload.js

提交回复
热议问题