在发布新的UI版本后,我们需要自动刷新缓存中的旧html、css和js文件,我读到添加查询版本(例如…js?v1(浏览器会向服务器询问当前版本,但要做到这一点,我需要修改缓存中已经存在的html文件
我还阅读了许多关于在html 中使用元标签的建议
<meta http-equiv="cache-control" content="no-cache" />
但是通过这种方式,浏览器总是会询问当前版本,这意味着许多服务器请求相同的文件
我试过使用
windows.location.reload(true);
但也不起作用
有一种方法使用javascript刷新禁用缓存
html文件大部分时间都没有缓存。根据我的经验,添加查询字符串非常有效,尤其是如果您使用的系统可以自动生成和添加查询字符串。同时禁用缓存将对加载时间产生负面影响。
你试图完成的事情的总体术语是";缓存破坏";。在谷歌上搜索这个以及你正在使用的服务器技术应该会提供几个简单的解决方案。
我找到了一个解决方案,通过REST API返回一个具有当前前端版本的头我在通用函数中添加了一个条件,该条件发送所有请求,将本地存储项与上次使用的版本和头中返回的版本进行比较
如果版本不同,则调用json来查找要刷新的文件,然后向每个项目发送一个post请求,这样浏览器就会更新文件。
// generic fuction to consume REST API
$.ajax({type: 'POST', url: base + url, dataType: 'json', async: true, data: data}).done(function (response, status, xhr) {
// the version returned by the REST API
let frontVersion = xhr.getResponseHeader('Front-Version');
if (localStorage.getItem('LS_FRONT_VERSION') !== frontVersion) {
// update the version the local storage
localStorage.setItem('LS_FRONT_VERSION', frontVersion);
// show an alert to the user
ui.alert('Reloading page...');
// function to reload files from a given array
let refresh=(items)=>{
//
let item = items.pop();
console.log('Reloading: ', item);
fetch(item, {method: "POST", body: ''})
.then(response => {
if (items.length === 0){
// if there is no more items, the page is refreshed
window.location.reload(true);
} else {
// call the refresh function without the last reloaded item
refresh(items);
}
});
};
// get from a file called items.json the list of files to reload
fetch('/js_project_lib/cache.json', {
method: 'POST',
body: null
})
.then(response => response.json())
.then(result => {
// call the refresh fuction with the items to be refreshed
refresh(result);
})
.catch(error => {
console.error('Error:', error);
});
}
}).fail(function (jqXHR, textStatus) {
}).always(function () {
});