I'm relatively new at JS, so I've had a hard time following the above answers to produce something workable. I finally did create something based off of Kennebec's answer above, but promptly received a dire warning from Chrome that calling XMLHttpRequest() synchronously is now deprecated, and will soon result in a script-crashing error.
So here's a plug-and-play script that will give you the modification time of a file on your server, gloriously asynchronous and compliant:
let file = "../yourfile.html";
function makeRequest(url) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
let rand = Math.floor(Math.random() * (99999 - 11111) + 11111);
let newurl = url+"?v="+rand;
xhr.open("HEAD", newurl);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.getResponseHeader("Last-Modified"));
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
document.onload = rando();
async function rando(){
let result = await makeRequest(file);
let time = Date.parse(result)/1000;
console.log(time);
}
Hope this helps save some time.
Incidentally, the reason I needed this script was to append a variable to dynamically-loaded CSS stylesheets. By using the modification time as the variable, it prevents the browser from caching the damn stylesheets if they've been modified since the last load. This is also a well-known trick for cache busting HTML files, but it's a lot easier to do in PHP!
async
method, so I had toawait fetch(xmlPath)...
, and also move the return statement outside of thefetch()
:return lastMod
– Political