Skip to content

Instantly share code, notes, and snippets.

@hunterwilhelm
Created January 14, 2022 00:37
Show Gist options
  • Save hunterwilhelm/49015425eb47e750807837859eed80ae to your computer and use it in GitHub Desktop.
Save hunterwilhelm/49015425eb47e750807837859eed80ae to your computer and use it in GitHub Desktop.
Cache busting made easy and reliable
/**
 * Reliably adds a cache bust param to the url
 * @param url: string
 * @returns string 
 */
function cacheBust(url) {
  const urlObject = new URL(url, window.location.origin);
  const paramsObject = new URLSearchParams(urlObject.search);
  paramsObject.set("cacheBust", (new Date().getTime()).toString(36));
  return `${urlObject.origin}${urlObject.pathname}?${paramsObject.toString()}`;
}

Examples:

cacheBust("http://localhost:8000")
// 'http://localhost:8000/?cacheBust=kydo6sdz'

cacheBust("/hello?existing=true")
// 'https://gist.github.com/hello?existing=true&cacheBust=kydo7i52'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment