如何在Javascript中缓存图像
我和我的朋友们在一个网站上工作,我们希望在其中缓存某些图像,以便将来更快地显示它们。我有两个主要问题:
- 您如何缓存图像?
- 图像被缓存后如何使用?(只是为了验证图像是否在页面A上缓存,可以从缓存中调用它以在页面B上使用它,对吗?)
此外,有可能设置 时, 图像的缓存版本将到期?
如果包括示例和/或进一步描述页面的链接,将不胜感激。
使用原始Javascript或jQuery版本都可以。
回答:
一旦将图像以任何方式加载到浏览器中,它将保存在浏览器缓存中,并且无论该图像是在当前页面还是在其他任何页面中使用,只要下次使用该图像,它将在下一次使用时更快地加载。在浏览器缓存过期之前使用。
因此,要预缓存图像,您要做的就是将它们加载到浏览器中。如果您要预缓存一堆图像,最好使用javascript来完成,因为使用javascript处理时通常不会阻止页面加载。您可以这样做:
function preloadImages(array) { if (!preloadImages.list) {
preloadImages.list = [];
}
var list = preloadImages.list;
for (var i = 0; i < array.length; i++) {
var img = new Image();
img.onload = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = array[i];
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);
可以根据需要多次调用此函数,每次都会将更多图像添加到预缓存中。
图片通过javascript预先加载后,浏览器会将其保存在缓存中,您可以仅在其他位置(在您的网页中)引用常规网址,浏览器将从缓存中获取该网址,而不是通过网络。
最终,随着时间的流逝,浏览器缓存可能会填满并扔掉一段时间未使用的最古老的东西。因此,最终,图像将被冲出缓存,但它们应在其中停留一段时间(取决于缓存的大小以及完成了多少其他浏览)。每次实际重新加载图像或在网页中使用图像时,图像都会自动刷新它们在浏览器缓存中的位置,因此不太可能将其从缓存中清除。
浏览器缓存是跨页面的,因此它适用于加载到浏览器中的任何页面。因此,您可以在站点中的一个地方预缓存,然后浏览器缓存将对站点中的所有其他页面起作用。
当按上述方式进行预缓存时,图像将异步加载,因此它们不会阻止页面的加载或显示。但是,如果您的页面上有很多自己的图像,则这些预缓存图像可以与带宽或与页面中显示的图像竞争连接。通常,这不是一个明显的问题,但是在连接速度较慢的情况下,这种预缓存可能会减慢主页的加载速度。如果可以最后一次加载预加载图像是可以的,那么您可以使用该函数的一个版本,该版本将等待开始预加载,直到所有其他页面资源都已加载完毕。
function preloadImages(array, waitForOtherResources, timeout) { var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15*1000, timer;
if (!preloadImages.list) {
preloadImages.list = [];
}
if (!waitForOtherResources || document.readyState === 'complete') {
loadNow();
} else {
window.addEventListener("load", function() {
clearTimeout(timer);
loadNow();
});
// in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
// then preload the images anyway after some timeout time
timer = setTimeout(loadNow, t);
}
function loadNow() {
if (!loaded) {
loaded = true;
for (var i = 0; i < imgs.length; i++) {
var img = new Image();
img.onload = img.onerror = img.onabort = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = imgs[i];
}
}
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"], true);
preloadImages(["url99.jpg", "url98.jpg"], true);
以上是 如何在Javascript中缓存图像 的全部内容, 来源链接: utcz.com/qa/398889.html