Skip to content
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

强缓存 #12

Open
YBFACC opened this issue Jun 6, 2020 · 0 comments
Open

强缓存 #12

YBFACC opened this issue Jun 6, 2020 · 0 comments

Comments

@YBFACC
Copy link
Owner

YBFACC commented Jun 6, 2020

强缓存

我的完整代码

使用好处

当 web 缓存发现请求的资源已经被存储,它会拦截请求,返回该资源的拷贝,而不会去源服务器重新下载。这样带来的好处有:缓解服务器端压力,提升性能(获取资源的耗时更短了)。对于网站来说,缓存是达到高性能的重要组成部分。MDN

按存储位置划分

  1. Service Worker(不涉及)

  2. Memory cache

  3. Disk cache

  4. Push Cache(不涉及)

属性一览

Cache-control(主流)

  • no-cache:强制要求缓存把请求提交给原始服务器进行验证(协商缓存验证)

  • no-store:不使用任何缓存。

  • private:只能被单个用户缓存,不能作为共享缓存。

  • public:表明响应可以被任何对象缓存。

  • max-age:设置缓存存储的最大周期(秒)。

Pragma(兼容)

  • no-cache:与 Cache-Control: no-cache 效果一致

MDN建议:只在需要兼容 HTTP/1.0 客户端的场合下应用 Pragma 首部

Expires(兼容)

声明资源的过期时间。有max-age的情况下,max-age优先。

测试

设置上Cache-control

给我的图片加上Cache-control

ctx.res.setHeader('Cache-control', 'public,max-age=86400')

请求页面后,我们看到服务器日志中,资源的请求都是正常的。

1

我们多次刷新页面。

300

可以看到图片已经缓存在内存中了,然后我们查看日志。

2

可以看到使用了缓存之后,服务器再没有收到请求。

测试 Expires 和 Cache-control 的优先级

  let exp = new Date()
  exp.setTime(exp.getTime() + 60000)//毫秒
  ctx.res.setHeader('Expires', exp.toUTCString())
  ctx.res.setHeader('Cache-control', 'public,max-age=86400')//秒

我们同时设置这两个属性。

3

等1分钟后刷新,还是强缓存状态。 Cache-control优先级更高。

决定使用 Memory cache 还是 Disk cache ?

这里我简单的做个测试发现:

  • 如果你短时间多次刷新(猛刷),Disk cache 会变成 Memory cache。
  • 对不同的文件有不同策略,css就容易进Disk cache。

这一块没有找到好的分享,以上的结论并不完全对。

参考

第7题-浏览器缓存命中策略

Cache-Control

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