How to generate a cachebuster in javascript code

Javascript cachebuster code

Programmatic websites often need files to be cached by the browser. There are many instances where a new file needs to be fetched from the server, each time a user takes an action. The cachebuster is the easiest way to request a file. In my line of work (marketing analytics and web development), we use the cachebuster to make sure browser makes a new request each time a page loads. This often means we want a new measurement of a page visit or we don't want duplicative page visit events being recorded to downstream systems. We will include the cachebuster value in a network call, so a new response is received from a server each time.

Sample Javascript Cachebuster Code

let random //define the variable 
//find a random number, multiply the random number, and round it to the nearest value
random = Math.round(Math.random() * 10000000000)
// display the random number in the browser console
console.log("Random cachebuster value " + random)


This is one example of a cachebuster. Some applications will accept a timestamp, instead of a random number. If you need to generate a cachebuster, there are three pieces of sample javascript code on my Github. Each piece of code can be used in applications that require a javascript cachebuster.

Comments