2

I have a page which needs to download an image file on onload event but, for all page calls! Now, it downloads the image in first call but in second call it gets from temporary and that is not the thing I want. I need to make some calculations for each load. So I want to delete the file that I download on each load from temporary or something else that forces client to download it from server again.

A javascript solution will be great. Thanks.

8

No, you can't do anything at all to the cache using Javascript, but you can change the url of the image so that it's not in the cache.

Just add a query string to the url of the image, and use the current time to make it unique each time:

<script type="text/javascript">
document.write('<img src="images/theImage.gif?t=' + new Date().getTime() + '" alt="" />');
</script>
| improve this answer | |
2

I understand you are looking for a javascript solution, but the good way to solve this is to use HTTP response headers which specify no-cache and expiry values. If you have no control over the web server configuration with .htaccess, you can create a simple PHP script that sets these headers before serving the content. In PHP:

header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
| improve this answer | |
2

Modify URL string to something like this:

originalUrl += "?" + new Date().getTime();
| improve this answer | |
1

I would set the HTTP header for the image that's being downloaded to Cache-Control : no-cache, rather than coming up with some javascript "hack".

| improve this answer | |
  • Good idea but the other solution is better for my problem. I prefer re-downloading to no-cache to whole page for this problem. Thanks by the way! – Ali Ersöz Mar 26 '09 at 8:38
  • IMHO you don't need to set the header for the whole page but for the image file only! For, downloading the image is performed by a separate HTTP request. On the other hand, since you use javascript for download anyway, using that hack seems appropriate to me. – chiccodoro Mar 26 '09 at 9:14
  • @chiccodoro, that's what I said, 'I would set the HTTP header for the image...'. :) – karim79 Mar 26 '09 at 9:34
1

You definitely can't delete a temporary file with javascript. To avoid caching use the no-cache header when sending the image. This way the image will be downloaded every time is requested.

List of headers here.

You must use:

Cache-Control: no-cache

This is Microsoft specific.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.