In this guide, we will look at two different methods. There are two ways to do this:
- Force the browser to use the newest version of our JS file.
Use the latest version.
The best method is to force the browser to use the newest version. We can do this by appending the version number of the file as a query string parameter:
<--include script with version as the query string-->
If the JS file goes unchanged, then the user’s browser will continue to cache it. However, if we update the file, then we can simply change the version parameter from 1.12 to something such as 1.13 or 1.14 (I typically use the version number that is present in my version control software – GIT, SVN, etc). Changing the version number will “bust the cache” by tricking the browser into thinking that it is a completely new file. The only drawback of this method is that you will have to modify the page that is including the script.
Never cache the file.
<--include script with current timestamp as the query string-->
<script src="myscript.js?t=<?= time(); ?>"></script>