What browser caching does
With browser caching, the browser stores files and reuses them on the next visit instead of loading them again. The server decides with headers how long that is allowed.
How it works
The Cache-Control header tells the browser what it may do with a file. With max-age=604800 it may use it for a week (604,800 seconds) without asking. With no-cache it has to ask every time, and with no-store it may not store it at all.
Asking is quick when the server sends a validator: an ETag (an identifier of the content) or Last-Modified (the date of change). The browser then asks "has this changed?", and the server answers 304 Not Modified without the file itself.
bytereport checks two things:
- Static files. CSS, JavaScript, images and fonts the HTML names, including those from foreign domains, should be kept by browsers for at least a week. If single files fall short, you get a warning; if more than half do, an error. bytereport reads
max-age, otherwiseExpires;no-cacheandno-storecount as not at all. - The page itself. If it sends neither
Cache-ControlnorETagnorLast-Modified, you get a hint.
What matters
- A year for files with a hash in their name. If the name changes with the content, such as
app.3f9a1c.js, the file can stay for a year; a new version gets a new name. - A week for other static files.
Cache-Control: max-age=604800is enough. - Have the page checked every time. HTML changes and should not sit unchecked in the cache for long. With
no-cacheand anETag, the browser checks briefly every time. - Third-party files. Their cache lifetime is set by the provider. If they are the problem, the only fix is to serve them yourself, see third parties.
Cache-Control: public, max-age=31536000, immutable
Cache-Control: no-cache
ETag: "5f2b-1a3c"
How to set it up
The headers are set by the web server, a CDN or, on shared hosting, the .htaccess file; caching plugins in the CMS often handle this. Whether file names get a hash is decided by the build tool or the theme. nginx and Apache send an ETag for static files on their own; for pages from PHP or a CMS, the application has to set it.
An example for a folder /assets/ with hashed file names (Apache needs mod_headers; the line goes into an .htaccess file in that folder):
For static files without a hash in their name, use max-age=604800 instead.