2017-01-04 11 views
1

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); 
} 
+0

为什么不使用localstorage,webstorage? – hubman

+0

我的理解是localStorage/sessionStorage不能存储图像文件。我知道有办法将图像编码为DataURI,但对于我的特定问题,这不是一个理想的解决方案。 –

+0

我试图澄清粗体句子。它原来措辞的方式听起来很奇怪(我的脑子在解析句子时偶然发现)。我正在做这个评论来验证OP,我没有意外地改变粗体语句的含义。 – Amy

回答

1

不,没有任何gua rantee。

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

+0

JavaScript可以访问缓存过期时间吗? –

+0

@Josh,我不认为这是可能的。即使知道过期时间,我也必须更新我的答案,但在过期时间之前缓存可能已满并且浏览器开始删除旧内容。 – Arashsoft