【问题标题】:Does keeping an image in memory prevent the cache of that image from expiring?将图像保存在内存中会阻止该图像的缓存过期吗?
【发布时间】:2017-01-04 21:27:32
【问题描述】:

preload Image files in JavaScript 的标准方式似乎是这样的:

var images_to_load = ['img1.png', 'img2.png', 'img3.png'];
for(var i=0; i<images_to_load.length; i++){
  var img = new Image();
  img.src = images_to_load[i];
}

这会通过让浏览器请求图像文件来将图像加载到缓存中。但是,不能保证图像文件会保留在缓存中,就像cache expiration time is dependent on server settings and browser settings

如果将 Image 对象保留在内存中,是否可以保证图像在页面关闭之前一直保留在缓存中?这是一个基本示例:

var images_to_load = ['img1.png', 'img2.png', 'img3.png'];
var loaded_images = [];
for(var i=0; i<images_to_load.length; i++){
  var img = new Image();
  img.src = images_to_load[i];
  loaded_images.push(img);
}

【问题讨论】:

  • 为什么不用localstorage、webstorage?
  • 据我了解localStorage/sessionStorage不能存储图片文件。我知道有一些方法可以将图像编码为 DataURI,但这不是解决我的特定问题的理想解决方案。
  • 我试图澄清粗体字。它最初的措辞对我来说听起来很奇怪(我的大脑在解析句子时绊倒了)。我发表此评论是为了向 OP 确认我没有意外更改粗体声明的含义。
  • 我很欣赏这个变化;措辞很尴尬。我试图改变它以保持更高的清晰度并保持原来的意思(这是询问这是否可能)。

标签: javascript browser-cache


【解决方案1】:

不,没有任何保证。

JavaScript 内存中的内容与浏览器缓存中的内容完全不同。一种可能的解决方案是在缓存过期时间之前创建图像的新实例。如果您重复此过程,您可以确保您的图像在缓存中始终可用。

【讨论】:

  • JavaScript 能否获取缓存过期时间?
  • @Josh,我认为这是不可能的。我必须更新我的答案,即使您知道过期时间,也有可能在过期时间之前缓存已满,浏览器开始删除旧内容。
【解决方案2】:

您可以使用服务工作者缓存甚至预加载图像

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers

有示例代码 https://github.com/mdn/sw-test/

在此处了解有关离线优先的更多信息:http://offlinefirst.org/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
相关资源
最近更新 更多