缓存动态加载的图像 [英] Caching dynamically loaded images
问题描述
我正在使用javascript根据用户互动动态地将任意系列图片加载到单个img标记中:
function reassignImage(newSource)
{
img.src = newSource;
}
除了我用Chrome开发人员工具检查它时,这很好用,
我看到即使我重新加载我已经加载的图像,它也会进行另一次http调用并增加整个图像大小图。
这似乎是两个世界中最糟糕的。我想要:
- 如果图像是
,则从缓存加载相同。 - 每次重新加载每张图片
,但不会增加
缓存。
我将如何实现这两种情况?
谢谢! Yarin
这将预加载图像,以便浏览器可以在您实际设置<$ c $时立即显示它c> src 的 img
标记。我推测预加载这样的图像将确保它在缓存中,因此它不会重新加载,但我还没有测试过。
var myImg = new Image(25,25);
myImg.src =/ foobar.png;
换句话说,现在应该只下载两张图片
function reassignImage(newSource){
var myImg = new Image(25,25);
myImg.src = newSource;
img.src = newSource;
}
reassignImage(first.png);
reassignImage(second.png);
reassignImage(first.png);
修改
<我做错了。尝试为用户加载的每个新文件创建
new Image()
。将这些图像元素交换进出dom。 < html>
< head>
< script>
var imageElements = {};
函数reassignImage(newSource){
if(typeof imageElements [newSource] ==undefined){
imageElements [newSource] = new Image();
imageElements [newSource] .src = newSource;
}
var container = document.getElementById(imageContainer);
container.innerHTML ='';
container.appendChild(imageElements [newSource]);
}
< / script>
< / head>
< body>
< div id =imageContainer>< / div>
< / body>
< / html>
I'm using javascript to dynamically load any of a series of images into a single img tag, based on user interaction:
function reassignImage(newSource)
{
img.src = newSource;
}
This works great, except that I when I inspect it with Chrome developer tools, I see that even if I reload an image I've already loaded, it makes another http call AND grows the total Images Size graph.
This seems like the worst of both worlds. I would want either:
- To load from cache if the image were the same.
- To reload each image everytime, but then not grow the cache.
How would I achieve either scenario?
Thanks! Yarin
This will pre-load an image so that the browser can display it immediately when you actually set the src
of an img
tag. I speculate that pre-loading an image like this will ensure it's in the cache so it won't reload, though I haven't tested it.
var myImg = new Image(25, 25);
myImg.src = "/foobar.png";
In other words, this should now hopefully only download two images
function reassignImage(newSource) {
var myImg = new Image(25, 25);
myImg.src = newSource;
img.src = newSource;
}
reassignImage("first.png");
reassignImage("second.png");
reassignImage("first.png");
Edit
I was doing it wrong. Try creating a new Image()
for every new file the user loads. Swap these image elements in and out of the dom.
<html>
<head>
<script>
var imageElements = {};
function reassignImage(newSource) {
if (typeof imageElements[newSource] == "undefined") {
imageElements[newSource] = new Image();
imageElements[newSource].src = newSource;
}
var container = document.getElementById("imageContainer");
container.innerHTML = '';
container.appendChild(imageElements[newSource]);
}
</script>
</head>
<body>
<div id="imageContainer"></div>
</body>
</html>
这篇关于缓存动态加载的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!