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>
Ive been wrong before but you might have meant:
Actually im wrong, you will need to do a document.write to write out the script tag i believe also.
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.
No it’s not, that’s not how JavaScript works. You need to do a document.write or else ?cb=cachebuster will be the exact thing sent to the server.
Actually, I was wrong. Yes we would need to use document.write to output the JavaScript tag. I will update my post to correct it.
where is external.js file….?????????
external.js file is the file that you want to add your cachebuster code to.
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)}})