Angular1.x 緩存問題
? 模板加載后,AngularJS會(huì)將它默認(rèn)緩存到 $templateCache
服務(wù)中柏腻。
在實(shí)際生產(chǎn)中泊业,可以提前將模板緩存到一個(gè)定義模板的JavaScript文件中逗扒,這
樣就不需要通過(guò)XHR來(lái)加載模板了$templateCache
服務(wù)允許 $http
服務(wù)緩存經(jīng)過(guò)XHR的模板請(qǐng)求寥院,
這樣它們就只會(huì)被請(qǐng)求一次。當(dāng)一個(gè)模板被取到了鼠证,它的內(nèi)容就會(huì)存儲(chǔ)在 $templateCache
中峡竣,用模板路徑作鍵。
例如量九,當(dāng)獲取下面的實(shí)例指令時(shí)适掰,它會(huì)請(qǐng)求 templateUrl 并且把模板的內(nèi)容放在 $templateCache
中:
angular.module('myApp').directive('notification', function($timeout) {
return {
restrict: 'A',
scope: { ngModel: '=' },
templateUrl: 'views/templates/notification.html',
}
});
$templateCache
會(huì) 把 這 個(gè) 模 板 的 內(nèi) 容 保 持 在$templateCache('views/templates/notification.html')
中。
? 如果已經(jīng)預(yù)先在$templateCache
中存放了測(cè)試所需的指令文件內(nèi)容,就可以使用$templateCache
來(lái)阻止在指令的單元測(cè)試中再產(chǎn)生請(qǐng)求攻谁≈晌椋可以使用優(yōu)秀的 karma-ng-html2js-preprocessor 包來(lái)把模板轉(zhuǎn)換成可在測(cè)試中使用的Angular模塊。利用 $templateCache
? 在生產(chǎn)中部署應(yīng)用時(shí)戚宦,我們都希望應(yīng)用的加載盡可能快个曙,以及盡可能做出響應(yīng)。使用XHR加載模板可能會(huì)導(dǎo)致Web應(yīng)用緩慢或者有卡頓的感覺受楼】寻幔可以通過(guò)將模板包裝為JavaScript文件,然后連同應(yīng)用程序的其他部分一起傳輸?shù)姆绞絺卧炷0寰彺婕虞d艳汽,而不是通過(guò)XHR提取模板猴贰。關(guān)于如何有效地包裝模板的詳細(xì)信息,請(qǐng)參考 $templateCache
工具: grunt-angular-templates 河狐。默認(rèn)情況下米绕,Angular無(wú)法從本地 $tempalteCache
中找到模板時(shí),會(huì)通過(guò)XHR提取模板馋艺。當(dāng)XHR請(qǐng)求很慢栅干,或者模板很大時(shí),它可能會(huì)對(duì)應(yīng)用的用戶體驗(yàn)造成很大的負(fù)面影響捐祠。
? 可以通過(guò)“偽造” $templateCache
已經(jīng)被填充的方式來(lái)避免這一延遲碱鳞,這樣Angular就不必從遠(yuǎn)程加載模板□庵可以在JavaScript中手動(dòng)實(shí)現(xiàn)這個(gè)技巧窿给,就像這樣:
angular.module('myApp',[])
.run(function($templateCache) {
$templateCache.put('home.html', 'This is the home template');
});
現(xiàn)在,當(dāng)Angular需要提取名為home.html的模板時(shí)率拒,它會(huì)在 $templateCahce 中找到它崩泡,而無(wú)需從服務(wù)器提取。
使用$templateCache
清除緩存
方法一
// 禁止模板緩存
app.run(function($rootScope, $templateCache) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (typeof(current) !== 'undefined'){
$templateCache.remove(current.templateUrl);
}
});
});
在配置 路由地址后俏橘,即在app.config
之后添加這段代碼允华,可禁止AngularJs將templateUrl
緩存起來(lái)。