背景
前端新版本上线后,部分用户打开页面有缓存,访问到旧页面,需清理缓存才可访问到最新资源。
问题分析
- 缓存有浏览器缓存和服务器缓存,最简单的解决办法是强制不使用缓存,但会降低用户体验并增加服务器压力。
- 最好是正常使用缓存策略,只解决新项目部署的缓存问题。
解决方法
SPA项目,项目文件包括index.html和打包后的资源文件,解决掉这两部分文件缓存问题。
- 资源文件:webpack打包时,对所有资源加入hash值,保证旧资源文件失效。
- index.html:
- 浏览器缓存,在头部加入不缓存声明。
<meta http-equiv="pragram" content="no-cache">
<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="expires" content="0">
- 服务器缓存,对index.html不缓存设置
location = /index.html {
add_header Cache-Control "no-cache, no-store";
}