When you visit a website for the first time, the browser usually caches the website’s assets (CSS, JavaScript, and image files) on your computer.
Caching is the process of saving a copy of a website’s page. This is done so that the next time you visit (or refresh) the page, some assets can be loaded from the computer.
The benefit of caching is that your computer will perform less requests to the website’s server, reducing internet bandwidth usage for both you and the server.
But the downside of caching is that when you change or update your website’s CSS, JavaScript, or image files, then those changes might not be immediately visible on your website.
This is because the browser serves the CSS file cached on the local computer instead of requesting a new copy from the server.
CSS versioning is a trick used to make the browser notice the change on your CSS file and request a new CSS file instead of serving one from the cache.
To use CSS versioning, you simply need to add a query string parameter on the href
attribute in your HTML page.
Consider the example below:
<link rel="stylesheet" href="style.css?v=2" />
The query string parameter ?v=2
after the style.css
file name is the CSS versioning trick.
Because of the query string parameter, the browser will think you are requesting a new file that has a different name than the cached one.
The one cached is style.css
, but the one requested is style.css?v=2
.
And that’s how you can avoid CSS caching with versioning.
The next time you update your CSS file again, you need to bump up the version of your CSS as follows:
<link rel="stylesheet" href="style.css?v=3" />
By updating the CSS version, any changes you made in the file will be immediately visible on the web page without needing to clear the browser cache first.
Versioning is only needed when you load external CSS files. Internal and inline CSS code is not cached because they are written on the HTML file of the web page that you requested.
I hope this tutorial has been useful for you 🙏