mochase / js-primer

js demos

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

浏览器的缓存策略

mochase opened this issue · comments

Cache-Control: no-store | no-cache | max-age=<seconds>

no-store: 没有缓存.

no-cache: 缓存但重新验证. 每次都会发送请求到服务器进行validate, 如果返回304(缓存有效), 则使用本地缓存.

max-age=: 设置缓存过期时间.

强缓存阶段

如果通过Cache-Control:max-age=<seconds> 或者Expires设置了缓存过期时间, 则在未过期的这段时间称为强缓存阶段, 这时请求会直接读取缓存

字段优先级: Cache-Control > Expires

协商缓存阶段

如果超过了缓存过期时间, 浏览器会先发送请求到服务器进行validate, 请求头上会带上If-None-Match, If-Modified-Since, 服务器比较这两个字段, 如果不需要更新, 返回304(缓存有效);否则返回新内容.

If-None-Match的值为Etag, If-Modified-Since的值为Last-Modified, EtagLast-Modified从之前服务器返回的response header中读取, 浏览器会记录.

字段优先级: Etag > Last-Modified

前端能干的事

通过meta标签设置缓存策略. 如使用

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

不使用缓存.