Caching static websites
Everything I know and do about caching for my static websites.
I care about performance. I also care about my users not downloading the same assets over and over again, when it does not make any sense. Caching is one of the most important aspects to achieve that. There are many pages on caching out there, but nothing that really answered my questions. So this is what I do.
Caching static assets
I cache my static assets super aggressively. They do not change and if they do, I make sure that users get the new version.
Cache policy for static assets
Cache-Control: public, max-age=31536000, immutable
What this means
public- The asset can be cached by any cache, even shared ones (like CDNs)max-age=31536000- The asset is valid for 1 year (31_536_000 seconds)immutable- The asset will never change. The browser does not even need to check.
What is included
.cssfiles.jsfiles- Images (
.png,.jpg,.webp, etc.) - Fonts (
.woff2, etc.) - Icons* (
.svg, more on that later)
How to bust the cache
Generated assets
For generated assets, so .js, generated srcset images and some .css files, I rely on the build process to generate unique filenames.
They are usually predictable by being based on the hash of the file, so they only change when the content changes. So if there is an updated file, the new file is fetched, otherwise we can continue to rely on the cache even after deploying.
Astro, Vite, Webpack and co do that out of the box.
global.css and icons.svg
Let me explain: some CSS I want to ship as a single file. I don’t want my build process to interfere, so that I can cache that even longer and more reliably. This goes into a global.css file, that I minify myself and include as a static asset.
For my icons, I mostly use an SVG sprite, a file containing all icons. This file can also be cached aggressively.
Read about sprite map performance here
To bust the cache for these two files, I append a version query parameter to the URL, e.g. /global.css?v1. This unique URL instructs the browser to fetch this version specifically.
Caching HTML files
So this one is tricky. HTML files ARE static, but they cannot be versioned like assets, because they are the entry point. Looking around the internet, there is no definite solutions. Most people do not cache HTML files at all, some cache them for a short time. There are etags and last-modified headers, but this is sometimes complex with CDNs.
Cache policy for HTML files
Cache-Control: max-age=180
Right now I only cache my HTML files for 3 minutes. I’m not yet convinced that this is the best solution, so I’ll update this post once I have more experience.