简体   繁体   English

Chrome不会缓存通过javascript设置的背景图片

[英]background-image set via javascript is not being cached by Chrome

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: 在我的网站上,加载页面时,一些javascript使用以下代码检测屏幕分辨率,然后将正文的背景设置为url:

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: 在url get_background/ ,使用以下PHP代码提供图像:

     $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. 在firefox中,所有这些均按预期工作。 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. 但是,在Chrome浏览器中,每次加载此站点上的页面时,图像似乎都会再次加载,而不仅仅是被缓存和提供。

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. 如果我将用于将背景设置为外部css文件的代码移动,则可以在chrome中按预期方式工作,但是,如果将其放在javascript中,则似乎会使Chrome刷新图像。

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. 由于需要通过JavaScript检测屏幕分辨率,因此必须将代码放在JS中。 Is there a way to force chrome to cache the image even though its loaded via javascript? 即使通过javascript加载了chrome,有没有办法强制chrome缓存图像?

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. 要成功缓存响应,您需要在初始响应中设置Expires标头,而在下一个响应中,您需要检查HTTP_IF_MODIFIED_SINCE请求标头的存在。

And if it exists - you need to respond back with 304 如果存在-您需要回覆304

More details may be found at http://dtbaker.com.au/random-bits/how-to-cache-images-generated-by-php.html 有关更多详细信息,请参见http://dtbaker.com.au/random-bits/how-to-cache-images-generation-by-php.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM