缓存的备用选项:状态提供程序中为false

时间:2017-01-30 04:30:45

标签: html angularjs html5 caching

我在我的状态下使用了cache:false来避免模板(html视图)缓存,如下所示。

.state('index.project_setup', {
        url: '/:customerTag/project-setup',
        templateUrl: 'app/views/common/customer/projects/setup_projects_wizard.html',
        data: { pageTitle: 'Project Setup' },
        cache: false
    })

将更改应用到html文件后,有时我需要硬刷新页面而不是重新加载。那是我缺少的东西,还是有办法完成这件事?

1 个答案:

答案 0 :(得分:0)

Angular模板缓存和浏览器缓存之间存在差异。 当Angular第一次加载模板时,它将触发该模板的AJAX请求,然后将HTML存储在名为$templateCache的服务中,因此如果再次需要完全相同的模板,它将跳过AJAX调用并将使用$templateCache中存储的HTML。

刷新页面后,$templateCache服务已初始化(因为所有JS都已初始化)并且所有缓存的HTML都已消失,因此当Angular需要HTML文件作为模板时,它将会触发AJAX第一次调用,将其存储在$templateCache中,然后从此处使用缓存的HTML。

另一方面,您的浏览器不会在每次刷新时“初始化”其缓存,因此如果您要请求之前缓存的文件,浏览器将跳过HTTP调用并将使用其缓存版本(如果有)

因此,假设我们需要名为x.html的模板,将会发生以下伪代码:

if (x.html exists in $templateCache)
    return x.html from $templateCache
else
    AngularJS perform HTTP GET for x.html
    if (browser has x.html cached version)
        return x.html from browser cache and don't fire HTTP request
    else
        fire HTTP request for x.html and return the result

这样你必须每隔一段时间“重新加载”你的模板。

我的开发解决方案是将更改的查询字符串附加到模板URL,例如:

.state('index.project_setup', {
        url: '/:customerTag/project-setup',
        templateUrl: 'app/views/common/customer/projects/setup_projects_wizard.html?v=' + Date.now(),
        data: { pageTitle: 'Project Setup' },
        cache: false
    })

这是一个简单的技巧,导致浏览器总是获取HTML文件,因为查询字符串永远不会相同(好吧,它会在1毫秒内相同:)),所以每次浏览器都会获取HTTP请求该HTML,它不会匹配以前的请求,也不会使用缓存。