如何缓存 angularjs 部分?

2023-12-09

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

目前代码如下:

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

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


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

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

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

本地存储作为缓存

如果我们想将模板保留在客户端上,我们可以使用本地存储以及。这角度本地存储扩展会简化很多事情。

那么,我们来调整一下run() to

  1. 观察local-storage,如果我们还没有template在客户端上
  2. 如果需要,发出加载最新版本的请求...
  3. 将其放入缓存中(local-storage and $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键/值并检查它。如果本地存储已过时...所有模板都必须重新加载。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何缓存 angularjs 部分? 的相关文章