我刚刚发现如果SVG中的图片的缓存控制头设置为no-cache
,Chrome不会缓存它们。而Firefox和IE10似乎会忽略这个设置。
我创建了一个包含静态SVG的测试页面:
HTML:
<div style="width: 500px; text-align: center;">
<input id="move-left-btn" type="button" value="<<">
<input id="move-right-btn" type="button" value=">>">
</div>
<div class="svgwrapper" style="width: 500px; height: 250px; background-color: lightgrey;">
<svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg" width="500" height="250">
<g id="svggroup" class="transition-on" transform="matrix(0.2,0,0,0.2,80,35)">
<image width="1672" height="887" opacity="1" xlink:href="https://dl.dropboxusercontent.com/sh/q7htlj5h8qqfhjf/SVDuynM7R3/car.png"></image>
</g>
</svg>
</div>
Javascript:
$(document).ready(function() {
var curXPos = 80;
// Local test function which represent some server calls in my "real life" scenario
// Just updates the x-position in the transform matrix in this test case
function updateSvgText(svgText, posXDelta) {
curXPos += posXDelta;
if (curXPos < 0) {
curXPos = 160;
} else if (curXPos > 160) {
curXPos = 0;
}
return svgText.replace(/matrix\(.*\)/, 'matrix(0.2,0,0,0.2,' + curXPos + ',35)');
}
// Fetch the new SVG (in real life from server) and rerender it
function moveSvg(posXDelta) {
var svg = $('#svg'),
svgText = updateSvgText($('.svgwrapper').html(), posXDelta);
svg.empty();
svg.append($(svgText).children());
}
$('#move-left-btn').click($.proxy(moveSvg, this, -20));
$('#move-right-btn').click($.proxy(moveSvg, this, 20));
});
使用
cache-control
头设置为no-cache
的示例(在“移动”按钮上按下后在Chrome中闪烁):
http://jsfiddle.net/zF6NF/4/使用
cache-control
头设置为max-age=315360000,public
的不同源图像的相同示例(没有闪烁):
http://jsfiddle.net/zF6NF/5/
在Chrome中,您可以看到第一个示例中每次按下按钮时图像重新加载(在开发工具的网络选项卡中可见),而Firefox在两个示例中都平滑地重新渲染SVG,而无需任何重新加载。
一些额外的信息:
这只是一个例子。在我的“实际情况”中,我从服务器接收一个新的SVG(而不是
updateSvgText
方法调用),这意味着我无法通过更改转换矩阵属性的值来执行SVG的部分更新,而是每次都必须重新渲染整个SVG(至少现在是这样...)。我无法控制图像的来源,这意味着两件事:
- 我无法更改
cache-control
头 - 我无法创建Base64编码的数据URI,将其保存在本地,并在渲染之前将SVG中的图像替换为那些数据URI(由于“相同资源来源”政策,无法创建Base64编码的数据URI...)
- 我无法更改
是否有任何方式可以...
- 即使图像来自不受控制的远程位置,也可以在本地覆盖/覆盖
cache-control
头吗? - 从客户端没有任何控制的不同域加载的图像中创建Base64编码的数据URI?
- 以某种方式告诉Chrome始终缓存我的SVG内部的图像?
不用说其他解决方案也非常欢迎!
谢谢
/matrix\([^)]*\)
或类似的东西。 - Sanjay Manohar