zoukankan      html  css  js  c++  java
  • angularJs $templateCache

      模板加载后,AngularJS会将它默认缓存到 $templateCache 服务中。在实际生产中,可以提前将模板缓存到一个定义模板的JavaScript文件中,这样就不需要通过XHR来加载模板了

      $templateCache 服务允许 $http 服务缓存经过XHR的模板请求,这样它们就只会被请求一次。当一个模板被取到了,它的内容就会存储在 $templateCache 中,用模板路径作键。例如,当获取下面的实例指令时,它会请求 templateUrl 并且把模板的内容放在 $templateCache 中:

    angular.module('myApp')
        .directive('notification', function($timeout) {
            return {
                restrict: 'A',
                scope: { ngModel: '=' },
                templateUrl: 'views/templates/notification.html',
    }});

    $templateCache 会 把 这 个 模 板 的 内 容 保 持 在 $templateCache('views/templates/notification.html') 中。如果已经预先在 $templateCache 中存放了测试所需的指令文件内容,就可以使用 $templateCache 来阻止在指令的单元测试中再产生请求。可以使用优秀的 karma-ng-html2js-preprocessor 包来把模板转换成可在测试中使用的Angular模块。

    利用 $templateCache
      在生产中部署应用时,我们都希望应用的加载尽可能快,以及尽可能做出响应。使用XHR加载模板可能会导致Web应用缓慢或者有卡顿的感觉。可以通过将模板包装为JavaScript文件,然后连同应用程序的其他部分一起传输的方式伪造模板缓存加载,而不是通过XHR提取模板。关于如何有效地包装模板的详细信息,请参考 $templateCache 工具: grunt-angular-templates 。

      默认情况下,Angular无法从本地 $tempalteCache 中找到模板时,会通过XHR提取模板。当XHR请求很慢,或者模板很大时,它可能会对应用的用户体验造成很大的负面影响。
      你可以通过“伪造” $templateCache 已经被填充的方式来避免这一延迟,这样Angular就不必从远程加载模板。可以在JavaScript中手动实现这个技巧,就像这样:

    angular.module('myApp',[])
        .run(function($templateCache) {
            $templateCache.put('home.html', 'This is the home template');
    });

      现在,当Angular需要提取名为home.html的模板时,它会在 $templateCahce 中找到它,而无需从服务器提取。

  • 相关阅读:
    优先队列实现哈弗曼最小权值
    最小生成树 克鲁斯卡尔(Kruskal)算法求最小生成树
    背包问题------
    背包问题------ 分类: ACM 2015-08-03 20:57 1人阅读 评论(0) 收藏
    Cent Savings (DP) 分类: ACM dp 2015-08-03 14:32 4人阅读 评论(0) 收藏
    Cent Savings (DP)
    Judging Troubles (multiset查找) 分类: ACM STL 2015-08-03 14:27 3人阅读 评论(0) 收藏
    Judging Troubles (multiset查找)
    Joke with permutation
    dubbo源码之二——dubbo入口
  • 原文地址:https://www.cnblogs.com/ms-grf/p/6874256.html
Copyright © 2011-2022 走看看