Cachebuster code in JavaScript

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>');
  1. Ive been wrong before but you might have meant:

  2. where is external.js file….?????????

  3. 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