浏览器缓存图像吗? [英] Do browsers cache images?

查看:135
本文介绍了浏览器缓存图像吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些Javascript的PHP页面,它在固定的时间间隔(5秒)之后改变IMG标签上的SRC属性。我有一个固定数量的图片,我循环。 PHP为所有图像URL构建一个字符串数组。

I have a PHP page with some Javascript that changes the SRC attribute on a IMG tag after a fixed interval of time (5 seconds). There is a fixed number of images that I cycle through. The PHP builds a string array for all the image URLs. The images are small most less than 10k.

如何判断浏览器是否缓存图像,如果不是,我该如何确保浏览器缓存图像?

How can I tell if the browser is caching the images and if not what must I do to ensure that a browser does cache them?

推荐答案

是的,浏览器会缓存它们,我发现最好的组合是发布必要的缓存控制标题,并在源URL中附加一个随机字符串。

Yes the browser will cache them, often even when your headers say otherwise. I have found the best combination is to issue the necessary Cache-Control headers along with appending a random string to the source URL.

例如,设置最长时间(秒):

Example, set the max age in seconds:

header("Cache-Control: max-age=3600");

然后在您的img源文件中附加一个随机字符串。这将需要在Javascript中,而不是在PHP中,因为一旦你的URL以PHP生成,它们将不会使用新的随机字符串进行更新:

Then append a random string to your img sources. This will need to be in Javascript, not in PHP because once your URLs are generated in PHP they won't keep updating with a new random string:

var randomString = "" + new Date().getTime();
var imageUrl = yourImageArray[someIndex] + "?" + randomString;

希望您明白。

这篇关于浏览器缓存图像吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆