Cachebuster code in JavaScript

The JavaScript, CSS and other files used in a website are often cached by the browser. Sometimes we might want the browser to always fetch the file from the server instead of from the cache. To do this we can use a cachebuster code to make the browser think that every time it is fetching a new file.

The following code can be used to generate a random value which can be used in JavaScript as a cachebuster value.

var cachebuster = Math.round(new Date().getTime() / 1000);

The above cachebuster value can be appended to the file to be included as a parameter.

Sample code:

<script type="text/javascript">
var cachebuster = Math.round(new Date().getTime() / 1000);
document.write('<scr'+'ipt type="text/javascript" src="external.js?cb=' +cachebuster+'"></scr' + 'ipt>');
</script>

Related posts:

  1. How to remove render blocking JavaScript with defer and async
  2. Get various parts of URL using JavaScript
  3. Voting Functionality in a website
  4. How to create CSV file using PHP

8 thoughts on “Cachebuster code in JavaScript”

      1. You don’t need to use document.write for script tag, because i have define “cachebuster” as a JavaScript variable to it is automatically replaced when the script is called.

  1. I wanted one to bust all PDFs. I use Jquery on the site. I wrote this from your script.

    $(‘a’).each(function(){if(this.href.indexOf(“.pdf”) !== -1){this.href += “?cb=” + Math.round(new Date().getTime() / 1000)}})

Leave a Reply