Post

Version push to cache in JavaScript

Sometimes we make changes in a CSS or JS file and it doesn’t show up. That’s because of the files being cached by the browser and it’s showing the old version. In PHP I had a variable that contains a version and echoed that behind the file path. In JS we can’t do exactly the same as we can not echo inline. So I made a snippet that’s using the same workflow of only changing 1 variable for all CSS and JS files. You only need to alter the value of pushVersion and it will refresh all CSS files with ?v=pushVersion in the file path. For JS files you need to addScript it on the bottom of the snippet to make it a dynamically loaded script with a version attached.

1
2
3
4
5
6
7
8
9
10
11
let pushVersion = "1.0.1d"
let baseUrl = window.location.href

Array.from(document.getElementsByTagName("link")).forEach((childLink) => { 
	const newHref = childLink.href.replaceAll('?v=pushVersion', `?v=${pushVersion}`)
	childLink.setAttribute('href', newHref)
})
const addScript = document.createElement("script")
addScript.setAttribute("src", `${baseUrl}/script.js?v=${pushVersion}`)
addScript.setAttribute("type", "text/javascript")
document.head.appendChild(addScript)
This post is licensed under CC BY 4.0 by the author.