模板加载后,AngularJS会将它默认缓存到 $templateCache 服务中。在实际生产中,能够提早将模板缓存到一个定义模板的JavaScript文件中,这样就不须要经过XHR来加载模板了html
$templateCache 服务容许 $http 服务缓存通过XHR的模板请求,这样它们就只会被请求一次。当一个模板被取到了,它的内容就会存储在 $templateCache 中,用模板路径做键。例如,当获取下面的实例指令时,它会请求 templateUrl 而且把模板的内容放在 $templateCache 中:缓存
1 angular.module('myApp') 2 .directive('notification', function($timeout) { 3 return { 4 restrict: 'A', 5 scope: { ngModel: '=' }, 6 templateUrl: 'views/templates/notification.html', 7 }});
$templateCache 会 把 这 个 模 板 的 内 容 保 持 在 $templateCache('views/templates/notification.html') 中。若是已经预先在 $templateCache 中存放了测试所需的指令文件内容,就可使用 $templateCache 来阻止在指令的单元测试中再产生请求。可使用优秀的 karma-ng-html2js-preprocessor 包来把模板转换成可在测试中使用的Angular模块。服务器
利用 $templateCache
在生产中部署应用时,咱们都但愿应用的加载尽量快,以及尽量作出响应。使用XHR加载模板可能会致使Web应用缓慢或者有卡顿的感受。能够经过将模板包装为JavaScript文件,而后连同应用程序的其余部分一块儿传输的方式伪造模板缓存加载,而不是经过XHR提取模板。关于如何有效地包装模板的详细信息,请参考 $templateCache 工具: grunt-angular-templates 。grunt
默认状况下,Angular没法从本地 $tempalteCache 中找到模板时,会经过XHR提取模板。当XHR请求很慢,或者模板很大时,它可能会对应用的用户体验形成很大的负面影响。
你能够经过“伪造” $templateCache 已经被填充的方式来避免这一延迟,这样Angular就没必要从远程加载模板。能够在JavaScript中手动实现这个技巧,就像这样:工具
1 angular.module('myApp',[]) 2 .run(function($templateCache) { 3 $templateCache.put('home.html', 'This is the home template'); 4 });
如今,当Angular须要提取名为home.html的模板时,它会在 $templateCahce 中找到它,而无需从服务器提取。单元测试