How to prevent caching of my Javascript file?

JavascriptCaching

Javascript Problem Overview


I have a simple html:

<html>
<body>
<head>
<meta charset="utf-8">
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
<script src="test.js"></script>
</body>
</html>

In test.js I changed a Javascript function, but my browser is caching this file. How to disable cache for script src?

Javascript Solutions


Solution 1 - Javascript

Add a random query string to the src

You could either do this manually by incrementing the querystring each time you make a change:

<script src="test.js?version=1"></script>

Or if you are using a server side language, you could automatically generate this:

ASP.NET:

<script src="test.js?rndstr=<%= getRandomStr() %>"></script>

More info on cache-busting can be found here:

https://www.curtiscode.dev/post/front-end-dev/what-is-cache-busting

Solution 2 - Javascript

<script src="test.js?random=<?php echo uniqid(); ?>"></script>

EDIT: Or you could use the file modification time so that it's cached on the client.

<script src="test.js?random=<?php echo filemtime('test.js'); ?>"></script>

Solution 3 - Javascript

Configure your webserver to send caching control HTTP headers for the script.

Fake headers in the HTML documents:

  1. Aren't as well supported as real HTTP headers
  2. Apply to the HTML document, not to resources that it links to

Solution 4 - Javascript

You can append a queryString to your src and change it only when you will release an updated version:

<script src="test.js?v=1"></script>

In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)

Solution 5 - Javascript

You can add a random (or datetime string) as query string to the url that points to your script. Like so:

<script type="text/javascript" src="test.js?q=123"></script> 

Every time you refresh the page you need to make sure the value of 'q' is changed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBdfyView Question on Stackoverflow
Solution 1 - JavascriptCurtisView Answer on Stackoverflow
Solution 2 - JavascriptAlex PliutauView Answer on Stackoverflow
Solution 3 - JavascriptQuentinView Answer on Stackoverflow
Solution 4 - JavascriptdaveoncodeView Answer on Stackoverflow
Solution 5 - JavascriptBas SlagterView Answer on Stackoverflow