【问题标题】:Create cached image twice with javascript使用 javascript 创建两次缓存图像
【发布时间】:2013-06-02 16:28:33
【问题描述】:
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。不幸的是,即使在 image2.src = someUrl; 语句之后,image1 也是被缓存的。

然而,有效的是缓存 image1,然后创建会话 cookie 并手动转到 someUrl 页面。然后它会缓存 image2。

不刷新页面就不能让浏览器缓存两次图片吗?

【问题讨论】:

  • 取决于您设置的缓存标头。当您加载 image2 时,添加一个带有当前时间戳的 last-changed 标头。这将使第一个无效。但同样,这取决于您为第一张图片设置的缓存设置
  • @TheBrain 你为两张图片推荐了哪些标题?
  • 新图片应具有不同的 URL 以确保下载。或者您需要在第一次下载时发送一个无缓存标头(尽管我不确定如果在同一页面上使用两个图像,浏览器如何处理这个问题)。

标签: php javascript caching


【解决方案1】:

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

var image1 = new Image();
image1.src = someUrl;

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

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

【讨论】:

    【解决方案2】:

    尝试在输出 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

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 1970-01-01
      • 2015-11-06
      • 2012-08-08
      • 2018-11-21
      • 1970-01-01
      • 2014-06-01
      • 2014-08-23
      • 1970-01-01
      相关资源
      最近更新 更多