I was reading this answer about how you can append the hash of a resource, such as a JS or CSS file to the filename, so that your browser only downloads it if it's changed, otherwise a cached version is used.
Why would you want to use this over the HTTP header Cache-Control: no-cache
?
Using a hash in the filename means you need to make sure the HTML containing the <script src="myscript.someHash.js"></script>
tags is never cached.
Why not allow the HTML (and all other resources) to be cacheable using no-cache
?
What's being discussed here are two different ways to cache pages while still ensuring correctness. This article does a good job of describing them, so I will use its terminology: Pattern 1 uses no-cache
on the HTML page, but creates unique filenames for each version of the static assets, and allows them to be cached forever. Pattern 2 just uses no-cache
for everything.
They both work. Pattern 1 will be strictly superior from a performance perspective, since only some of its pages have no-cache
. The only downside is that the build workflow is more complicated, since you need to generate unique filenames and make sure your HTML page links to them properly. Fortunately, many frameworks support this kind of workflow.
It seems like your main concern is that "you need to make sure the HTML containing the [static links] is never cached." But it can still be cached, it just needs to be revalidated every time it's used. But that's true of every file in Pattern 2, so it isn't a comparative disadvantage.