2014-12-05 35 views
5

我注意到,在對我的角應用程序進行全面刷新時,狀態轉換(我使用ui-router,但也可能類似於本地Angular路由)第一次訪問,因爲瀏覽器執行GET請求來檢索與給定狀態相關聯的HTML部分。隨後的所有訪問基本上都是即時的,但我想知道是否有方法告訴Angular在首次訪問頁面時預加載所有必需的部分內容?將HTML部分預加載到AngularJS UI-Router應用程序

他們不這樣做,因爲如果並行獲取最終太多的部分會使用太多的帶寬?

回答

5

您可以將這些部分放在腳本標記中,並將它放在主HTML頁面中,以便它們全部放在前面。你也可以加載它們在你的應用程序的運行塊,並把它們在$templateCache

$templateCache.put('template.html', '<h1>My template</h1>');

或從服務器得到它,如果它不是內聯:

$http.get('template.html', {cache:$templateCache});

+0

嘿抱歉沒有看到您的答案。我可能會使用後者,只是在應用程序初始化期間獲取partials。這是最有意義的。謝謝! – 2015-05-12 20:59:41

3

要在應用程序初始化預壓模板,你可以使用:

angular 
.module('app') 
.run(['$state', '$templateCache', '$http', 
    function ($state, $templateCache, $http) { 
     angular.forEach($state.get(), function (state, key) { 
      if (state.templateUrl !== undefined && state.preload !== false) { 
       $http.get(state.templateUrl, {cache: $templateCache}); 
      } 
     }); 
    } 
]); 

這將預裝所有templa除非在狀態定義中設置了preload: false,否則默認爲默認值。

感謝Sobieck的回答here爲概念,我修改爲使用ui-router

0

這裏是一個解決方案,將做到這一點,並將處理任何定義的意見。

run(['$state', '$templateCache', '$http', function($state, $templateCache, $http) { 
    var url; 
    function preload(v){ 
     if(v.preload){ 
      if(url = v.templateUrl){ 
       $http.get(url, { cache: $templateCache }); 
      } 
     } 
     // state has multiple views. See if they need to be preloaded. 
     if(v.views){ 
      for(var i in v.views){ 
       // I have seen views with a views property. 
       // Not sure if it's standard but won't hurt to support them 
       preload(v.views[i]); 
      } 
     } 
    } 
    $state.get().forEach(preload); 
}]) 

您可以輕鬆更改此默認與if(v.preload === false){更換4號線(if(v.preload){)預加載。基於this answer

相關問題