AngularJS中的按需加载ocLazyLoad插件应用;
一、前言
ocLoayLoad是AngularJS的模块按需加载器。一般在小型项目里,首次加载页面就下载好所有的资源没有什么大问题。但是当我们的网站渐渐庞大起来,这样子的加载策略让网速初始化速度变得越来越慢,用户体验不好。二来,分模块加载易于团队协作,减低代码冲突。
二、按需加载的对象
各个Controller模块、Directive模块、Server模块、template模板,其实这些都是一些 .js文件或者 .html文件 。
三 、按需加载的场景
1 路由加载(resolve/uiRouter)
基于uiRouter的resolve是在加载controller和template之前所执行的一系列操作,它帮助我们初始化我们所要前往的那一个视图。只有be solved(操作完成),controller才会被实例化。因此,我们可以在resolve步骤里面加载我们所需要的controller。
.state('weiindex', {
url: "/weiindex",
cache: false,
templateUrl: "templates/weiindex.html",
controller: 'weiindexCtrl',
resolve: {
loadMyCtrl: function($ocLazyLoad){
return $ocLazyLoad.load('js/weiindexCtrl.js');
}
}
})
其中,'js/weiindexCtrl.js'里面放着一个我们所需要的controller
angular.module('myApp')
.controller('weiindexCtrl', ['$scope', function($scope){
//...
}])
2 依赖加载
在依赖项里面导入我们所需要的一系列模块(这里有一层'[ ]'符合哦)
angular.module('touchModule', [[
'lib/file/touch.js',
'lib/file/iscroll.js'
]]).controller('touchModuleCtrl', ['$scope', function($scope){
//...
}])
3 Cotroller里动态加载
angular.module('myApp')
.controller('weiindexCtrl', ['$scope','$ocLazyLoad', function($scope, $ocLazyLoad){
$scope.loadBootstrap = function(){
$ocLazyLoad.load([
'lib/bootstrap/dist/js/bootstrap.js',
'lib/bootstrap/dist/css/bootstrap.css'
])
}
var unbind = $scope.$on('ocLazyLoad.fileLoaded', function(e, file){
$scope.bootstrapLoaded = true;
console.log('下载boot完成');
unbind();
})
}])
4 template包含加载(config)
如何处理我们所加载的html模板里面嵌套的controller呢?这里需要oc-lazy-load指令和$ocLazyLoadProvider的配置
/*template A.html*/
<h1>hi i am hzp </h1>
<div oc-lazy-load="touchModule">
<div ng-controller="touchModuleCtrl">
<span>{{test}}</span><br/>
<div ui-grid="touchOptions" class="touchStyle"></div>
</div>
</div>
</div>
$ocLazyLoadProvider.config({
modules: [{
name: 'touchModule',
files: [
'js/touchModule.js'
]
}]
})
四、如何组织按需加载
分路由、按功能来区分、打包成不同的多个或单个controller.directive.server模块

浙公网安备 33010602011771号