用javascript创建两次缓存图像

Create cached image twice with javascript

本文关键字:两次 缓存 图像 javascript 创建      更新时间:2023-09-26
var image1 = new Image();
image1.src = someUrl;
// someUrl is a valid URL to a PHP file which outputs a PNG file using the imagepng function. This action caches image1 to someUrl.
image1.onload = function() {
    // Some things have changed and a new image is created, which I would like to cache to someUrl.
    // This is currently done by sending a session (temporary) cookie, which is recognised by the PHP file, so that it knows to take different action than the first time.
    // Again, the imagepng function is used to output the image.
    var image2 = new Image();
    image2.src = someUrl; // this is the exact same URL
};

期望的结果是让浏览器缓存image2作为缓存的image1的替换。不幸的是,image1是缓存的,甚至在image2.src = someUrl;语句之后。

但是,

的工作原理是缓存image1,然后创建会话cookie并手动转到someUrl页面。然后缓存image2。

是不是不可能让浏览器缓存图像两次,而不刷新页面?

您可以尝试在url中添加任意参数。例如:

var image1 = new Image();
image1.src = someUrl;
var image2 = new Image();
image2.src = someUrl + '?action=cache'; // or timestamp

这将欺骗浏览器将image2视为新图像,同时仍然加载该图像(假设您没有在GET中发送任何其他参数,在这种情况下使用'&'而不是'?')

尝试在输出png的php文件中使用缓存控制头。例如

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

来源:http://php.net/manual/en/function.header.php