Is it possible to access the file creation time of an <img> src in javascript?

html, image, javascript

Solution

It transpires that Apache seems to send the last-modified time as a header by default. Getting hold of this header is not possible simply by using a javascript method as you describe. You could do it in a not 100% reliable or effecient way by re-downloading the file using AJAX, and checking the last modified time of the re-downloaded image (which will almost always be the same as the original).

using a little jQuery for the AJAX call...

<img id="my_img" src="images/current.png" />

<!-- include jQuery - better done in the head -->
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

<script language="javascript">
var i = document.getElementById('my_img');
$.get(i.src,function(data,status,xhr){
    // in the callback - after the ajax request completes...
    var filetime = xhr.getResponseHeader('Last-Modified');
    i.title = 'image created: ' + filetime; // don't care about formating now
})
</script>

This method will only work when the server sends the correct `Last-Modified` header, and it might be different (although usually not) than the image previously loaded, and causes extra traffic and requests by re-downloading the image you want the timestamp for.

If possible - I think a better solution is to get the server to expose the timestamps of files via a small data feed, maybe sending JSON showing last-modified and other meta data for each file based on the filename as a key... so the server should send something like this:

{
    "images/current.png":{"last-modified":"2012-08-07","filesize":"1056 kb"},
    "images/raisin.png":{"last-modified":"2012-08-04","filesize":"334 kb"},
    "images/sultana.png":{"last-modified":"2012-08-02","filesize":"934 kb"}
}

Which would then be easy to parse client side (using `JSON.parse()`) and determine all the filesizes you need - more efficiently and reliably.

Problem

Given the following example ``` <img id="my_img" src="images/current.png" /> <script language="javascript"> var i = document.getElementById('my_img'); var filetime = i.is_there_any_method_for_this(); // ????? i.title = 'image created: ' + filetime; // don't care about formating now </script> ``` I'd like to ask if `is_there_any_method_for_this();` exists or if it's at all possible to access the file creation (or modification) time of the displayed image.

Original source