Cached files are locally stored versions of your file in the users browser. The first time a user visits your website, those files may be downloaded and stored in their memory (browser cache); so that the next time they visit, the browser can load the page quicker by just loading the cahced versions.
Cache expires after some time, but before it does, your users may complain about broken functionaltiy or not getting the right user experience. You usually don’t run into such issues if you are using a framework or CDN that allows you to flush cache for all users. But, if you’re not, then there are easy ways to fix this. So, how to force and reload browser cache?
Add a GET version variable to your file
For example, if you were linking your file:
You can add a GET variable with the version of your file. For example:
Now, whenever you change the file, you can update the version number and it will trick the browser into reloading the file as a new file. It will then be cached for the user, until you changed the version number again. You can also use this to correspond with your own versioning system to keep track of files (and rolling back to a previous version shouldn’t be a problem too). You can also use the date the file was saved as the version number.
Always load a new version of the file
If, for some reason, you always want a fresh file to be loaded for the user, you can follow the same GET variable idea, but with a random string attached. For example, if you use PHP, you can use the rand(); function
https://www.example.com/js/script.js?v=<?php echo rand(); ?>
Now, everytime this this script runs, there will be a random string attached to it tricking the browser into thinking that this is a new file, and reloading it again.
Though this is not an ideal way to do things, as it is counter-productive to caching. Caching helps with load times, as if the file is the same, the browser shouldn’t need to download it again. So be sure that you have a good reason to use this random method.
Since I first wrote this post on my old blog (and then moved it here), I found another solution on Stack Overflow that uses Apache URL rewrite rules and a small function to automaticaly assign a version to the filename. The function is written in PHP, but you can code the same function in any other language.
This isn’t the most ideal way though. As you may have guessed, this means a new file is loaded everytime for the user. Caching is useful in improving load times for repeating users/visitors, and this is counter-productive to that. We need a better solution