Reputation: 267177
On my web site, while the page is loaded, some javascript detects the screen resolution and then sets the body's background to be a url, using this code:
var url = "http://site.com/get_background/" + width + "/" + height;
var body=document.getElementsByTagName('body')[0];
body.style.background = "#000000 url(" + url + ") fixed top center";
At the url get_background/
, an image is served using the following PHP code:
$etag = md5_file($image);
$lastModified = gmdate('D, d M Y H:i:s', filemtime($image)) . ' GMT';
header("Content-type: $mime");
header("ETag: \"{$etag}\"");
header("Last-Modified: $lastModified");
header('Cache-Control: max-age=28800');
$image = readfile($image);
imagejpeg($image);
imagejpeg($image);
In firefox, this all works as expected. However in Chrome, each time a page on this site loads, the image seems to get loaded once again rather than just being cached and served.
If I move the code for setting the background to an external css file, then it works as expected in chrome, however if I put it in javascript, then it seems to make Chrome refresh the image.
What should I do about it? As the screen resolution needs to be detected via javascript, therefore the code must be put in the JS. Is there a way to force chrome to cache the image even though its loaded via javascript?
Upvotes: 0
Views: 1047
Reputation: 255005
To successfully cache the response you need to set Expires
header in the initial response and on next responses you need to check existence of HTTP_IF_MODIFIED_SINCE
request header.
And if it exists - you need to respond back with 304
More details may be found at http://dtbaker.com.au/random-bits/how-to-cache-images-generated-by-php.html
Upvotes: 1