Caching best practices & max-age gotchas

In notebook:
Article Notes
Created at:
DOM Performance

Content type 1: can cache for a long time:

​Cache-control: max-age=31536000

This means content is good to be cached for a year. If you need to update a file, e.g. a script file, you add a versioning number to the file name. e.g. script-eg432if.js

Content type 2: Might change, need to validate with the server

​Cache-control: no-cache

The browser cache will cache the contents but will validate it with the server before using it.
​no-store​ means the browser should not cache it at all
​must-revalidate​ means local cached resource can be used if it’s younger than ​max-age

You add an ​ETag​ or ​Last-Modified​ to the reponse that determines wether the browser uses the cache or need to fetch the resource from the server.

Using max-age on mutable content

Usually not a good choice

​Cache-Control: must-revalidate, max-age=600

If the cache has some of the files but not all, it might use the outdated files (the ones it has), while giving a new version of the file it didn’t have.

A page refresh usually forces the browser to revalidate the cache and thus fixes this. But doesn’t give a good impression.

With service workers you can mix the above two strategies: use server revalidation for the root page and immutable content (max-age) for resources. This way you can do small, incremental updates of your webb app, only updating atomic files.
  const version = '23';

self.addEventListener('install', event => {
      .then(cache => cache.addAll([