详解AngularJS通过ocLazyLoad实现动态(懒)加载模块和依赖
糖粑粑 人气:0最近在使用AngularJS,发现AngularJS菜鸟教程上的东西太过于基础,很多东西都没有提及,比如今天的一个关于前端的优化问题,懒加载。通过路由实现地址分发的时候,再通过懒加载模式加载你所需的文件,比如是相关的controller,就是js,这样有利于提高首次加载的负担。
下面就是一个懒加载的实现过程。
实现的过程主要是引用3个主要的JS文件:
<script src="angular/1.4.8/angular/angular.min.js"></script> <script src="angular/ui-router/release/angular-ui-router.min.js"></script> <script src="angular/oclazyload/src/ocLazyLoad.min.js"></script>
然后通过 APP 配置,将依赖的脚本进行注入操作:
var app = angular.module('pkcms', ["ui.router", "oc.lazyLoad"]); app.config(["$provide", "$compileProvider", "$controllerProvider", "$filterProvider", function ($provide, $compileProvider, $controllerProvider, $filterProvider) { app.controller = $controllerProvider.register; app.directive = $compileProvider.directive; app.filter = $filterProvider.register; app.factory = $provide.factory; app.service = $provide.service; app.constant = $provide.constant; }]); // 按模块化加载其他的脚本文件 app.constant('Modules_Config', [ { name: 'treeControl', serie: true, files: [ "Scripts/angular-bootstrap/ui-bootstrap-tpls-0.14.3.min.js" ]<br>}]); app.config(["$ocLazyLoadProvider","Modules_Config",routeFn]); function routeFn($ocLazyLoadProvider,Modules_Config){ $ocLazyLoadProvider.config({ debug:false, events:false, modules:Modules_Config }); };
以上是初始化动态加载的配置过程。
接着是建立路由:
"use strict" app.config(["$stateProvider","$urlRouterProvider",routeFn]); function routeFn($stateProvider,$urlRouterProvider){ $urlRouterProvider.otherwise("/main"); $stateProvider .state("main",{ url:"/main", templateUrl:"views/main.html", controller:"mainCtrl", controllerAs:"main", resolve:{ deps:["$ocLazyLoad",function($ocLazyLoad){ return $ocLazyLoad.load("controllers/main.js"); }] } }) .state("adminUser",{ url:"/adminUser", templateUrl:"views/adminUser.html", controller:"adminUserCtrl", controllerAs:"adminUser", resolve:{ deps:["$ocLazyLoad",function($ocLazyLoad){ return $ocLazyLoad.load("controllers/adminUser.js"); }] } }) };
最后是按路由配置的在对应目录下建2个HTML页面文件和2个JS文件用做测试
main.html
<div> {{main.value}} </div> adminUser.html <div> {{adminUser.value}} </div>
main.js
/** * mainCtrl * Created by pkcms.cn on 2016/6/24. */ (function () { "use strict" app.controller("mainCtrl", mainCtrlFn); function mainCtrlFn() { this.value = "Hello World"; } }())
adminUser.js
/** * adminUserCtrlFn * Created by pkcms.cn on 2016/6/24. */ (function () { app.controller('adminUserCtrl',adminUserCtrlFn); function adminUserCtrlFn() { this.value = "welcome to admin user"; } }());
加载全部内容