阻止浏览器对html的缓存

问题由来:版本更新后,项目打包上线,打包后的js、css等静态资源的名称已变化(打包工具),不必担心它们的缓存,而html文件未改变(如index.html),浏览器仍会使用缓存的html文件,导致各种错误

1. 后端设置get请求的response请求头

response.setDateHeader("Expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");

2. 前端使用js向href添加随机参数(注意:若为hash模式,则随机参数需要放置在 # 前)

if (!window.name) {
  location.href += "?random=" + Date.now();
  window.name = "reloaded";
}

3. 在html的head中添加meta(浏览器仍希望缓存的话无效)

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

猜你喜欢

转载自blog.csdn.net/qq_33576343/article/details/85146561
今日推荐