I may be fundamentally misunderstanding something here but it seems to me that if I want to fetch something I can call
let r = await fetch("someurl");
and the browser will use a cached version if it has one. Or I could call
let r = await fetch("someurl", {
cache: "reload"
});
and I would always get a new version.
What I cannot find is how to tell it that I only want the cached version if it is younger than X minutes.
I could do
let r = await fetch("someurl", {
headers: {
"Cache-control": "max-age=180"
}
});
but afaiu that would just get sent to the server and not actually impact what the browser is doing about values in its own cache.
2
Answers
You’re on the right track, but your understanding is slightly off. When you use the cache option in the fetch API, you’re controlling how the browser fetches resources from its cache or from the network. The "reload" option does indeed force the browser to bypass its cache and fetch a fresh version from the network.
In theory you can actually do exactly what you said:
That’s because
Cache-Control
is a request header as well as a response header:My impression in the past was that browser caches don’t respect this request header, though, so I’m not sure offhand how well this will work in practice.