1、前端缓存问题描述
最近前端项目(vue)发版时用户反馈,新发布功能使用异常,有报错。 经过分析发现主要由以下原因造成:
1.1 nginx 设置缓存为
expires 3d;
前端刷新或者保持页面不动则则会请求报错
1.2 前端资源是懒加载造成。并且是覆盖发布,
发布后修改的js服务器端不再存在,造成部分功能出现问题。
2、关于浏览器缓存原因的研究
2.1 浏览器默认缓存
Chrome和Firefox对js、css之类的文件,在内存中的缓存时长,是: (访问时间 - 该文件的最后修改时间) ÷ 10
假设文件 a.js 最后编辑时间是 2018年12月1号 10点0分0秒; Chrome的第一次访问时间是 2018年12月1号 12点0分0秒; 第一次访问与文件编辑时间相差2小时,即7200秒,那么缓存时长就是720秒 即结论如下:
- 1、在 2018年12月1号 12点0分1秒到 12点11分59秒,这12分钟内,浏览器不会发起http请求;
- 2、在 2018年12月1号 12点12分0秒,会发起带 If-Modified-Since 的http请求
- 3、如果希望浏览器每次都发起http请求,请在WebServer返回Header Cache-Control: no-cache
3、解决缓存最佳设置
以nginx为例:设置js缓存,根路径,即html不缓存。
# 前端静态文件
location ~* \.(gif|jpg|jpeg|png|css|js|ico|eot|otf|fon|font|ttf|ttc|woff|woff2)$ {
root /var/www/example-fe/dist/;
expires 1M;
add_header Cache-Control "public";
}
# 前端html文件
location / {
# disable cache html
add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
4、其他解决办法
4.1 html meta属性(不能根本解决问题)
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache" content="no-cache">