How to prevent Browser from caching JavaScript file

Sometimes, JavaScript modification doesn’t reflect on the page while running the need to clear browser cache manually each time when the file gets updated.

It makes the debugging process hard.

If the project contains some bug and you fix it but the user needs to clear the browser cache to reflect the changes.

In this tutorial, I show how you can prevent JavaScript file from Caching by the browser.

How to prevent Browser from caching JavaScript file


Contents

  1. Separate File
  2. Random String
  3. Dynamically Change version
  4. Conclusion

1. Separate File

  • First, you need to copy your JavaScript code in a separate file if you managing it within the same page with HTML and server-side code.
  • Include the created script file in your file.

2. Random String

Add a random string to src attribute while including the script in your file.

<script src='script.js?version=1'></script>

You need to update the version value each time you made changes to the code.

Example –

<script src='script.js?version=2'></script>

Each time when a page is loaded then browser view it as a new file and load it.


3. Dynamically Change version

If you are using the Server-side script in your project e.g. PHP then you can make it dynamic and don’t need to update the value each time when you modify the file.

<script src='script.js?version=<?= time() ?>'></script>

I have added PHP time() function to make random string value unique you can also use a uniqid() function.

<script src='script.js?random=<?= uniqid() ?>'></script>

4. Conclusion

If you are using Server-side scripting in your project then it is better to make custom string value dynamic instead of updating it manually.

Follow the same steps if you want to prevent caching CSS files.

If you found this tutorial helpful then don't forget to share.