Skip to content

浏览器的缓存 #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
lurenacm opened this issue Jun 11, 2021 · 0 comments
Open

浏览器的缓存 #1

lurenacm opened this issue Jun 11, 2021 · 0 comments

Comments

@lurenacm
Copy link
Owner

浏览器的缓存

所谓浏览器的缓存,就是浏览器通过 HTTP 请求网络资源后将资源留在本地的一种行为。在页面上点击 返回和前进的按钮 就是利用浏览器的缓存。

  • 浏览器的缓存分为两种 强缓存协商缓存
  • 浏览器缓存资源的位置放置四个地方 Service Worker, Memory Cache, Disk Cache, Push CacheService Worker 优先级最高到 Push Cache

浏览器请求资源过程

先本地再服务器

  • 浏览器请求资源时会先去判断本地缓存资源的 header 是否有命中强缓存,如果命中强缓存则直接请求本地的资源,不向服务器发送请求。
  • 如果没有命中强缓存或强缓存失效以后就会发送 HTTP请求服务器,这个过程采用的就是协商缓存

简单的说浏览器的缓存请求分为有无 HTTP 请求两种。

强缓存

所谓的强缓存是我们没有发送 HTTP 请求,而是直接从本地缓存中获取资源的一种行为。成功后返回状态码 200。

  • 浏览器是根据响应头的 headers 字段判断 Expires/http1.0Cache-Control/http1.1,来执行强缓存的过程。
  • 没有或失效的强缓存,浏览器会向服务器发送请求资源。

Expires

http1.0 中一个页面的缓存字段,是一个格林时间。这个时间是浏览器强缓存资源失效的时间

Expires: Wed, 22 Nov 2021 08:41:00 GMT

上面的表示缓存的资源会在 2021年11月22号8点41分 过期。

  • 缺点:浏览器是根据本地的时间判断资源是否过期的,但是本地的时间可以被修改,所以在HTTP1.1Expires 被放弃了。

Cache-Control

HTTP1.1 中页面的缓存字段,如果 Expires和Cache-Control 都存在,那么Cache-Control的优先级更高。

  • Cache-Control 的属性值有很多,其中属性 max-age 表示,一个相对的缓存时间
Cache-Control: max-age = 3600

表示距离上次请求的一小时内可以直接使用本地的缓存。不需要再次请求。

  • 属性 public 表示可以被浏览器或代理服务器缓存。
  • 属性 private 表示只能被浏览器缓存。
  • 属性 no-cache 需要发送请求到服务器确认是否被缓存,这需要使用到协商缓存。
  • 属性 no-store 表示禁止使用缓存,每一次都需要请求服务器。

协商缓存

所谓协商缓存是指:

参考

《图解HTTP》
浏览器缓存
前端缓存

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant