javascript XMLHttpRequest:如何强制缓存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28154796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XMLHttpRequest: How to force caching?
提问by user3631654
I'm newer to XMLHttpRequests since I've previously used jQuery's AjAX method. However I need to work in a web worker and now I have to use the classic XMLHttpRequest for performance issues.
我对 XMLHttpRequests 比较陌生,因为我以前使用过 jQuery 的 AjAX 方法。但是,我需要在网络工作者中工作,现在我必须使用经典的 XMLHttpRequest 来解决性能问题。
I'm trying to rebuild the cache
-property from jquery. If cache should be disabled I add this:
我正在尝试cache
从 jquery重建-property。如果缓存应该被禁用,我添加这个:
xhr.setRequestHeader("Cache-Control", "no-cache");
But what header should I set if I want to force caching (not prevent)?
但是如果我想强制缓存(而不是阻止),我应该设置什么标头?
采纳答案by Quentin
There are a variety of headers you can set to encourage caching, but they (including Cache-Control
which you are using incorrectly) are responseheaders that must be sent by the server and not request headers.
您可以设置多种标头来鼓励缓存,但它们(包括Cache-Control
您使用不正确的标头)是必须由服务器发送的响应标头,而不是请求标头。
One such example of using Cache-Control:
使用 Cache-Control 的示例之一:
Cache-Control: max-age=3600
This Caching Tutorial for Web Authors and Webmasterscovers them in more depth.
这个面向 Web 作者和网站管理员的缓存教程更深入地介绍了它们。
回答by Franklin Yu
You can specify max-stale
without an argument, in Cache-Control
header of your request. From RFC 7234:
您可以在max-stale
不带参数的情况下在请求的Cache-Control
标头中指定。来自RFC 7234:
The
max-stale
request directive indicates that the client is willing to accept a response that has exceeded its freshness lifetime. Ifmax-stale
is assigned a value, then the client is willing to accept a response that has exceeded its freshness lifetime by no more than the specified number of seconds. If no value is assigned tomax-stale
, then the client is willing to accept a stale response of any age.
该
max-stale
请求指令表明该客户愿意接受已超过其使用寿命新鲜的响应。如果max-stale
分配了一个值,则客户端愿意接受超过其新鲜度生命周期不超过指定秒数的响应。如果没有为 分配值max-stale
,则客户端愿意接受任何年龄的陈旧响应。