问题
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
回答1:
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>
回答2:
What's the cache-control header set to in the http response for the image? (Chrome developer tools will show you). If it's not set to be cacheable, it will get refetched.
回答3:
Technically you can set it this way in .htaccess file:
# Set up caching on images for 1 month
<FilesMatch "\.(jpg|jpeg|png|ico|gif)$">
ExpiresDefault A2419200
</FilesMatch>
If you would like with this settings force image to refresh, append this to its URL:
'?'+ new Date().getTime()
来源:https://stackoverflow.com/questions/3712234/caching-dynamically-loaded-images