SoFunction
Updated on 2025-04-10

On-demand loading example of angularJS+requireJS implementing controller and directive

Recently, because the project is relatively large, there are many js files that need to be loaded. In order to improve the loading speed of the first screen page, the js files need to be loaded on demand. Then I referenced some information online, and after a thorough study, I realized the effect of loading the controller js files and command js files on demand;

The idea is as follows

1. Use the resolve attribute in ui-router to achieve preloading

2. You need to use $controllerProvider to register the controller dynamically, and $compileProvider to register the command dynamically.

3. You need to use $q to help us achieve asynchronous loading. The specific steps are as follows;

1. Mount the properties of the registration controller and directive on the module we defined (in the js file of definition()), as shown below

 = {//Note that the $controllerProvider here is the property of the built-in registration controller, and $compileProvider is the property of the built-in registration directive
    controller: $,

    directive: $

   } 

2. Use $q to define a method to load a js file asynchronously (in the js file that defines the route)

 = function(js){
        return function($rootScope, $q){
          var deffer = $(),
            deps=[];
          (js) ? (deps = js) : (js);
          require(deps,function(){
            $rootScope.$apply(function(){
              ();
            });
          });
          return ;
        };
      }

3. With the help of the resolve attribute in the route, configure the controller file and instruction file that needs to be loaded (in the js file that defines the route)

.state('view1',{
      url: '/view1',
      templateUrl: 'temp/',
      controller: 'MyCtrl1',
      resolve:{
//Contact js files that require dynamic loading, other js files and so on        deps:(['./controllers/my-ctrl-1','./directives/loading'])
      }
    })

4. Dynamically register the controller or command by first step

//Register the controller (in the corresponding controller js file)('MyCtrl1', function ($scope,$css,$rootScope) {
    //Content in the controller    
  });

//Register command (in the corresponding command js file)
("loading",function (){

return {
restrict: "AE",
replace: true,
template: "<div class='mask' ng-show='isLoading'><span>loading</span></div>"
}
});  

If there is a service or filter that needs to be loaded on demand, it is also a similar method. In addition, if it is a public service, directive or filter and other files that do not require on demand can be defined using the normal () method;

Finally, this is just an idea to implement the loading of js files on demand. The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I hope everyone will support me more.