在iframe中加载后,图像不会从缓存中加载

我正在iframe中加载图像,然后(一旦加载了iframe)在页面上加载图像。 但是大多数浏览器似乎都在加载图像两次。 为什么不从缓存中加载img标记?

像这样的东西:

 var loader = $('').appendTo('body')[0]; loader.onload = function() { $('body').append(''); }; loader.src = imgsrc; 

http://jsfiddle.net/amirshim/na3UA/

我正在使用fiddler2来查看网络流量。

如果您想知道我为什么要这样做,请查看此问题

拥有iframe就像有一个单独的选项卡,它使用另一个浏览器实例,因此我认为它不使用缓存。

如果您想要的是预先加载图片,您可以在javascript中使用new Image()

也许你发送HTTP标头,这阻止了缓存? 如果您使用PHP将图像发送给用户并启动会话,PHP将设置标题强制一直重新加载图像。

.htaccess可用于改进缓存,您也可以在PHP中设置标头。 我使用.htaccess:如果图像已加载一次并且您没有进行任何更改,它将从缓存加载。 可以为其他类型的文件设置此行为(请参见下文):

的.htaccess

 https://stackoverflow.com/questions/4981229/image-not-loading-from-cache-after-its-loaded-in-an-iframe/# BEGIN Expire headers  ExpiresActive On ExpiresDefault "access plus 1 seconds" ExpiresByType image/x-icon "access plus 2 months" ExpiresByType image/jpeg "access plus 2 months" ExpiresByType image/png "access plus 2 months" ExpiresByType image/gif "access plus 2 months" ExpiresByType application/x-shockwave-flash "access plus 2 months" ExpiresByType text/css A15552000 ExpiresByType text/javascript "access plus 2 months" ExpiresByType application/x-javascript "access plus 2 months" ExpiresByType text/html "access plus 600 seconds" ExpiresByType application/xhtml+xml "access plus 600 seconds"  https://stackoverflow.com/questions/4981229/image-not-loading-from-cache-after-its-loaded-in-an-iframe/# END Expire headers https://stackoverflow.com/questions/4981229/image-not-loading-from-cache-after-its-loaded-in-an-iframe/# BEGIN Cache-Control Headers   Header set Cache-Control "max-age=15552000, public"   Header set Cache-Control "max-age=2678400, public"   Header set Cache-Control "max-age=2678400, private"   Header set Cache-Control "max-age=600, private, must-revalidate"  

我已经测试了这个新版本并且它可以工作,缓存用于第二个图像,在IE7和FF3.6上测试。 区别在于我在load()jQuery回调中设置img src属性的方式(但为什么对我来说仍然是一个谜)。

在这个例子中要小心我用一个巨大的图像来真正看到差异。

 $(function() { var use_unique_name = true; var imgsrc = 'http://www.challey.com/WTC/wtc_huge.jpg'; if (use_unique_name) { var ts = +(new Date()); // try replacing _= if it is there var ret = imgsrc.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end imgsrc = imgsrc + ((ret == imgsrc) ? (imgsrc.match(/\?/) ? "&" : "?") + "_=" + ts : ""); } var loader = $('').appendTo('body'); loader.load(function() { var img = jQuery(''); $('body').append(img); img.attr('src',imgsrc); }); loader.attr('src', imgsrc); }); 

编辑小提琴链接: http : //jsfiddle.net/regilero/g8Hfw/