【问题标题】:Preloading HTML partials into AngularJS UI-Router application将 HTML 部分预加载到 AngularJS UI-Router 应用程序中
【发布时间】:2015-02-03 06:15:58
【问题描述】:

我注意到,在完全刷新我的 Angular 应用程序时,状态转换(我使用的是 ui-router,但可能也类似于原生 Angular 路由)在第一次访问时会有轻微的延迟,因为浏览器会发出 GET 请求检索与该给定状态关联的 HTML 部分。所有后续访问基本上都是即时的,但我想知道是否有办法告诉 Angular 在第一次进入页面时预加载所有需要的部分?

他们这样做不是因为如果并行获取最终太多的部分会占用太多的带宽吗?

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    您可以将这些部分放在脚本标记中,并将其放在您的主 HTML 页面中,这样它们就会全部加载到前面。您也可以将它们加载到应用程序的运行块中,并将它们放在$templateCache

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

    如果不是内联的,也可以从服务器获取:

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

    【讨论】:

    • 嘿抱歉没有看到你的答案。我可能会使用后者,并在应用程序初始化期间获取部分内容。这是最有意义的。谢谢!
    【解决方案2】:

    要在应用程序初始化时预加载模板,您可以使用:

    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});
                }
            });
        }
    ]);
    

    这将默认预加载所有 templateUrls,除非在状态定义中设置了 preload: false

    感谢 Sobieck 对 here 的概念的回答,我对其进行了修改以与 ui-router 一起使用。

    【讨论】:

      【解决方案3】:

      这是一个解决方案,可以做到这一点并处理任何定义的视图。

      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);
      }])
      

      您可以通过将第 4 行 (if(v.preload){) 替换为 if(v.preload === false){ 轻松地将其更改为默认预加载。

      基于this answer

      【讨论】:

        猜你喜欢
        • 2017-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-10
        • 2013-04-08
        • 2017-05-12
        • 1970-01-01
        • 2016-12-22
        相关资源
        最近更新 更多