Detailed explanation of requireJs loading js on demand based on angular routing

  • 2021-07-13 03:49:50
  • OfStack

I'm finally not busy recently! ! Have time to precipitate the angular things you learned before! !

angular routing must be no stranger to everyone! (Strangers go to see my previous article to teach you how to configure angular routing!)

As a single page application, angular routing is one page when switching pages, so switching controller and loading control js on demand becomes a big problem! ! After tossing me for a long time, the built-in method of angular-route did not solve this problem, and finally I solved this problem with requireJs! ! Code!

1. First introduce requireJs and write configuration requirejs (['framework']) with a closure underneath it, which means to enter the page for the first time and load framework


<script src="js/lib/require.min.js"></script> 
<script> 
  (function () { 
    var jsDir = '/js/'; 
    var jsLibDir = '/js/lib/'; 
    var jsComponentDir = '/components/'; 
    var paths = { 
      angular: jsLibDir + 'angular.min', 
      angularRoute: jsLibDir + 'angular-route.min', 
      jquery: jsLibDir + 'jquery.min', 
      jQueryMD5: jsLibDir + 'jquery.md5', 
      highcharts: jsLibDir + 'highcharts', 
      radialProgress: jsLibDir + 'radialProgress', 
      d3: jsLibDir + 'd3.min', 
      echarts: jsLibDir + 'echarts', 
      framework: jsDir + 'framework', 
      angularUtil: jsDir + 'angular-util', 
      standardDashboard: jsDir + 'standard-dashboard', 
      standardConsole: jsDir + 'standard-console', 
      standardAmountStatistic: jsDir + 'standard-amount-statistic', 
      standardReport: jsDir + 'standard-report', 
      standardAdvancedReport: jsDir + 'standard-advanced-report', 
      standardExpertAnswer: jsDir + 'standard-expert-answer', 
      standardService: jsDir + 'standard-service', 
      standardStrategyInform: jsDir + 'standard-strategy-inform', 
      standardMember: jsDir + 'standard-member', 
      standardSchedule: jsDir + 'standard-schedule', 
      standardChannel: jsDir + 'standard-channel', 
      standardStrategyMerge: jsDir + 'standard-strategy-merge', 
      standardIntegrate: jsDir + 'standard-integrate', 
      standardPersonalCenter: jsDir + 'standard-personal-center', 
      dateTimePicker: jsComponentDir + 'dateTimePicker/date-time-picker', 
      fullCalendar: jsComponentDir + 'fullCalendar/fullcalendar', 
      moment: jsComponentDir + 'fullCalendar/moment' 
    }; 
     
    requirejs.config({ 
      paths: paths, 
      shim: { 
        angular: { 
          exports : 'angular', 
          deps: ['jquery'] 
        }, 
        angularRoute: { 
          deps: ['angular'] 
        }, 
        jQueryMD5: { 
          deps: ['jquery'] 
        } 
      }, 
      //urlArgs: "timeStamp=" + (new Date()).getTime() 
      //urlArgs: 'v=1.47.1&t=20160719' 
    }); 
    requirejs(['framework']); 
  }()); 
</script> 

2. framework. js, as the first loaded js, plays a vital role! ! Define frameworkApp module as the main module, load public service utilmodel and ngRoute routes, define an resolveController method, and the callback function is requireJs, which will be discussed later!


// Introducing module  
var frameworkApp = angular.module('FrameworkApp',['ngRoute', 'utilModule']); 
// Load the corresponding controller 
var resolveController = function (names, dependancies) { 
  //console.log(names) 
  //console.log(dependancies) 
  return { 
    loadController: ['$q', '$rootScope', function ($q, $rootScope) { 
      var defer = $q.defer(); 
      require(names, function () { 
        defer.resolve(); 
        $rootScope.$apply(); 
      }); 
      return defer.promise; 
    }] 
  }; 
}; 

3. Configure the route and use the resolve method to complete the callback. Note that the callback is an list, and the value is the module name defined in step 1


frameworkApp.config(['$routeProvider', '$controllerProvider', '$provide', '$compileProvider', '$filterProvider', 
  function ($routeProvider, $controllerProvider, $provide, $compileProvider, $filterProvider) { 
    frameworkApp.register = { 
      controller: $controllerProvider.register, 
      factory: $provide.factory, 
      service: $provide.service, 
      filter: $filterProvider.register, 
      directive: $compileProvider.directive 
    }; 
    $routeProvider 
      .when('/',{ 
        redirectTo: '/dashboard' 
      }) 
      .when('/dashboard',{ 
        templateUrl: 'dashboard.html', 
        controller: 'DashboardCtrl', 
        resolve: resolveController(['standardDashboard', 'd3','radialProgress','highcharts']) 
      }) 
      .when('/console',{ 
        templateUrl: 'console.html', 
        controller: 'ConsoleCtrl', 
        resolve: resolveController(['standardConsole']) 
      }) 
      .when('/amountStatistic',{ 
        templateUrl: 'amount-statistic.html', 
        controller: 'amountStatisticCtrl', 
        resolve: resolveController(['standardAmountStatistic','highcharts','dateTimePicker']) 
      }) 
      .when('/report',{ 
        templateUrl: 'report.html', 
        controller: 'ReportCtrl', 
        resolve: resolveController(['standardReport','dateTimePicker']) 
      }) 
      .when('/advancedReport',{ 
        templateUrl: 'advanced-report.html', 
        controller: 'advancedReportCtrl', 
        resolve: resolveController(['standardAdvancedReport','highcharts','dateTimePicker']) 
      }) 
      .when('/expertAnswer',{ 
        templateUrl: 'expert-answer.html', 
        controller: 'expertAnswerCtrl', 
        resolve: resolveController(['standardExpertAnswer']) 
      }) 
      .when('/service',{ 
        templateUrl: 'service.html', 
        controller: 'ServiceCtrl', 
        resolve: resolveController(['standardService']) 
      }) 
      .when('/strategy-inform',{ 
        templateUrl: 'strategy-inform.html', 
        controller: 'StrategyInformCtrl', 
        resolve: resolveController(['standardStrategyInform']) 
      }) 
      .when('/member',{ 
        templateUrl: 'member.html', 
        controller: 'MemberCtrl', 
        resolve: resolveController(['standardMember']) 
      }) 
      .when('/schedule',{ 
        templateUrl: 'schedule.html', 
        controller: 'ScheduleCtrl', 
        resolve: resolveController(['standardSchedule']) 
      }) 
      .when('/channel',{ 
        templateUrl: 'channel.html', 
        controller: 'ChannelCtrl', 
        resolve: resolveController(['standardChannel']) 
      }) 
      .when('/strategy-merge',{ 
        templateUrl: 'strategy-merge.html', 
        controller: 'StrategyMergeCtrl', 
        resolve: resolveController(['standardStrategyMerge']) 
      }) 
      .when('/integrate',{ 
        templateUrl: 'integrate.html', 
        controller: 'IntegrateCtrl', 
        resolve: resolveController(['standardIntegrate']) 
      }) 
      .when('/personalCenter',{ 
        templateUrl: 'personal-center.html', 
        controller: 'PersonalCenterCtrl', 
        resolve: resolveController(['standardPersonalCenter']) 
      }) 
      .otherwise({ 
        redirectTo: '/error' 
      }); 
 
  }]); 

4. You're done ~ complete controller switching and js loading on demand! ! ! La la la!

5. I didn't solve one point either. When introducing echarts, I reported an error in this way. It was ok to replace it with highcharts. I didn't introduce echarts for a long time, but I found that it was ok to introduce echarts before require came into effect! Ask the great God to explain it! !


<!-- start build --> 
  <script src="js/lib/echarts.js"></script> 
  <script src="js/lib/require.min.js"></script> 

Related articles: