What is Cache Busting?
Cache busting is a technique so that browsers can have long caches on files while having them reload files when they change. Before you can understand that, you have to understand how caching works with websites.
Caching Your Website
When you want browsers to cache files so that users don’t have to reload them every time they visit your website, you use HTTP caching. HTTP caching allows you to specify how long a cache should be held for a file name, so that loading the page is pretty fast. Now let’s look into the problem.
The Problem with Caching
Imagine you have a website with 3 files,
index.css and you set the cache lifetime to 1 year so that the website loads pretty fast. Now you change the
index.css to have a different color scheme across your app. Your old users wouldn’t notice because they would have to wait a year for the cache to refresh.
That becomes a problem, especially when deploying bug fixes and security patches. People typically use cache busting to solve this, where they use various ways to change the names of the files that are loading for every version so that browsers will load them and add them to their cache.
There are a couple different ways of changing the names of files so that they will load when they change. One way is to use version numbers and have them somewhere in the file name when loading. You could have a subdirectory for every version,
v2/index.css. You could also have the version in queries in the URLs,
Another way is to change the name of the file,
index.v2.css. These ways are not as manageable because this can become very hard once you have a ton of files that are being changed.
A more popular and manageable way is to keep hashes inside the file names. Hashes, if you don’t know, are fixed length character representations of any content and they are irreversible, meaning you can get the hash from the file but you can’t get the file from the hash. Hashes are perfect for this, because when a file changes its hash will change, so if we keep the hash inside the filename
index.[someHashHere].js browsers will detect it and load it instead of an old file.
In this post I talked about the problem with having long caches without cache busting and different ways to cache bust your app.