PDA

View Full Version : How to know if image loaded from cache or not?



leonid.ge
07-30-2010, 09:05 AM
Hello!

I need to know if an image was loaded from cache or from the server.

image = new Image();
image.src = "http://...";

I have a callback function that is called when image is loaded.

I need to count (on server side) how many times the image was accessed on the server (not in browser cache).

Meanwhile I calculate the time which it took image to load and if the time is "large" (means image loaded from server) I call server php script which increases count.

But I have a problem to establish the correct time threshold.

Is there an exact way to know if image was loaded from cache or not?

Thanks in advance...

jscheuer1
07-31-2010, 03:44 AM
I don't think so. However, you can force the browser to make a fresh request by appending a unique query string. The best way to do that in javascript is to use the current date/time stamp. For example:


var im = new Image(), imsrc = 'http//www.somedomain.com/images/some.jpg';
im.onload = function(){
// do whatever you want/need here for the image's onload event
}
im.src = imsrc + '?bustcache=' + new Date().getTime();

This will force the browser to fetch the image anew from the server because new Date().getTime(); will always be a unique number, a number that is larger than the last and all previous times.

leonid.ge
08-05-2010, 01:28 PM
I don't think so. However, you can force the browser to make a fresh request by appending a unique query string. The best way to do that in javascript is to use the current date/time stamp. For example:


var im = new Image(), imsrc = 'http//www.somedomain.com/images/some.jpg';
im.onload = function(){
// do whatever you want/need here for the image's onload event
}
im.src = imsrc + '?bustcache=' + new Date().getTime();

This will force the browser to fetch the image anew from the server because new Date().getTime(); will always be a unique number, a number that is larger than the last and all previous times.

Thank you, but this is exactly what I don't want to do as I've got many images and I want them to load quickly from cache.

Only when a fresh image is loaded from the server I want to count this event.

jscheuer1
08-05-2010, 04:03 PM
If you have to count on the server side, that would be a server side script, not a javascript. However, as long as the URL (highlighted) used here (from your first post):



image = new Image();
image.src = "http://...";

is to a cached image, the browser will use that cached image.

The server may or may not see that as a request though, I really don't know that much about that in this particular situation. What server side language are you using? If it's PHP, the PHP forum here is pretty good, and may be able to answer that question, and the larger question of how to count when a file is requested and/or actually sent.