【问题标题】:how to cache angularjs partials?如何缓存angularjs部分?
【发布时间】:2014-01-20 08:40:45
【问题描述】:

在 angularjs 生产中缓存局部的最简单/现代的方法是什么?

目前代码如下:

$routeProvider.when('/error', {templateUrl: 'partials/error.html', controller: 'ErrorCtrl'});

templateUrl 显然是一个单独文件的 http 路径。在移动设备上,该文件的加载时间很明显,我很想缓存所有内容。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    答案的主要部分是$templateCache。摘录:

    var myApp = angular.module('myApp', []);
    myApp.run(function($templateCache) {
        $templateCache.put('templateId.html', 'This is the content of the template');
    });
    

    任何 html 模板,都可以移动到$templateCache,我们的应用程序的其余部分将按预期运行(无需其他更改)

    本地存储作为缓存

    如果我们想将模板保留在客户端,我们也可以使用本地存储。这个angular-local-storage 扩展会简化很多东西。

    所以,让我们将run() 调整为

    1. 观察local-storage,如果我们在客户端还没有模板
    2. 如果需要,发出加载最新的请求...
    3. 将其放入缓存中(local-storage$templateCache

    调整后的代码

    .run([                  'localStorageService','$templateCache','$http',
        function myAppConfig(localStorageService , $templateCache , $http) {
    
        // The clearAll() should be called if we need clear the local storage
        // the best is by checking the previously stored value, e.g. version constant 
        // localStorageService.clearAll();
    
        var templateKey = "TheRealPathToTheTemplate.tpl.html";
    
        // is it already loaded?
        var template = localStorageService.get(templateKey);
    
        // load the template and cache it 
        if (!template) {
            $http.get(templateKey)
                .then(function(response) {
    
                    // template loaded from the server
                    template = response.data;
    
                    localStorageService.add(templateKey, template);
                    $templateCache.put(templateKey, template);
                });
        } else {
    
            // inject the template
            $templateCache.put(templateKey, template);
        }
    
        }])
    

    因此,通过这种方式,我们确实可以从local-storage 中获利。它充满了来自服务器的“模板”,保存在那里......因此下次不会加载。

    注意:注入一些version 键/值并检查它也很重要。如果本地存储已过时...必须重新加载所有模板。

    【讨论】:

    • 我的部分文件很大,我宁愿它们不在一个大文件中。我可以从静态文件中加载 $templateCache 中的部分吗?
    • 我已经更新了答案。如果我确实正确理解了您的问题,我们可以做的是使用本地存储。这将(与 $templateCache 合作)完成这项工作......加载一次。
    • 与此有关,我刚刚遇到的一种情况,如果你使用$http.get()将模板加载到$templateCache类似上面,有可能是之前没有加载模板route 需要模板,因此未正确加载,有没有办法可以将它附加到解析对象或类似的东西?
    • @NinjaPants 我理解,即使在运行中调用,承诺也可以在以后解决。但在这种情况下,$templateCache 不应该被填充,模板会被直接加载。同时 get 将完成,下一次,本地存储被填充。它对我有用。但是,如果您提出新问题,您可以传递更多详细信息(您的代码),并且有人可以快速找到......因为,我的回答中的上述方法 - 对我有用。至少对我来说;)
    • 这里的答案是:如果我们不尽快预加载 - 那么这将会发生:Angular 在它需要模板的时候询问$templateCache。所有已处理的模板 (cached) 都将可用。任何缺失,都会立即强制调用服务器来获取该模板。因此,我们正在努力实现的目标是找到最佳位置,在哪里预加载所有“重”模板,在用户接触它们之前。在需要之前将它们放入$templateCache(和本地存储)。只有在这种情况下,我们才会去他们一次。是回答吗?
    猜你喜欢
    • 1970-01-01
    • 2019-03-08
    • 2014-09-06
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多