Dmitry Dmitry - 5 months ago 19
Ajax Question

How to get Javascript Last-Modified date

I know,

document.lastModified
returns a string containing the date and time on which the current document was last modified.

Does it possible to get Last-Modified for script?

HTML

...
<script id="myapp" type="text/javascript" src="https://test.asl.cloud/cc/js/my-app.js"></script>
...
<button onclick="myFunction()">Try it</button>
<p id="test_doc"></p>
<p id="test_js"></p>
...


Javascript

myFunction = function() {
var x = document.lastModified;
document.getElementById("test_doc").innerHTML = x;

var se = document.getElementsByTagName('script');
var s;
for (var i = 0; i < se.length; i++) {
if (typeof se[i].src !== 'undefined' && se[i].src.match('cloud')) {
s = se[i];
break;
}
}
console.log(s);
x = s.lastModified;
document.getElementById("test_js").innerHTML = x;
}


JSFiddle

Answer

One way to approach this would be to do an AJAX request for the script, then read the Last-Modified header there.

var client = new XMLHttpRequest();
client.open("GET", "myscript.js", true);
client.onreadystatechange = function() {
  if(this.readyState == 2) {
    console.log(client.getResponseHeader("Last-Modified"));
  }
}
client.send();

For example, the above code with https://code.jquery.com/jquery-3.0.0.js instead of myscript.js would log:

Thu, 09 Jun 2016 18:32:50 GMT