【发布时间】:2020-06-26 21:32:15
【问题描述】:
对于延迟加载可视化,我正在尝试仅将淡入动画样式类应用于尚未在浏览器中缓存的图像。
要确定图像之前是否已加载并缓存在浏览器中,我们可以在如下函数中使用 HTMLImageElement.complete 属性:
const isImageCached = (imageSource) => {
let image = new Image();
image.src = imageSource;
const isCached = image.complete;
image.src = "";
image = null;
return isCached;
};
但是,在 Chrome 中,HTTP 缓存项位于 memory cache 或 disk cache。上述函数仅在图像在memory cache 中时有效,如果图像在disk cache 中,则始终返回 false。我认为这是因为内存会在 0 毫秒内立即被访问,而磁盘缓存可能需要长达几毫秒的时间才能被检索到。
当您第一次打开并运行上述脚本时,图像会淡入,因为它尚未缓存在浏览器中。当您通过按“运行” 按钮重新运行脚本时,图像不会淡入,因为它现在缓存在 Chrome 的 memory cache 中。如果内存缓存已被清除,则会出现此问题。图片已经被缓存,但现在它可能位于disk cache,所以图片会淡入。
下面是 Chrome 开发人员工具的屏幕截图,详细说明了刷新页面时的输出 (disk cache),然后脚本在不刷新页面的情况下重新运行 (memory cache):
在显示图像之前,是否可以在 JavaScript 中确定图像是否位于 HTTP 缓存中,memory cache 或 disk cache?
const image = document.querySelector("img");
const marioSrc = "https://www.pinclipart.com/picdir/big/361-3619269_mario-16-bit-mario-bros-super-mario-world.png";
const isImageCached = (imageSource) => {
let image = new Image();
image.src = imageSource;
const result = image.complete;
image.src = "";
image = null;
return result;
};
if (!isImageCached(marioSrc)) {
image.classList.add("image-fade-in");
}
image.setAttribute("src", marioSrc);
:root {
margin: 0;
padding: 0;
}
body {
background-color: #444444;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
overflow-y: hidden;
}
@keyframes fade-in {
0% { opacity: 0; }
100% { opacity: 1; }
}
.image-fade-in {
animation: fade-in 1s ease-in-out;
}
<img />
【问题讨论】:
-
我记得一些“利用”可以通过检查加载时间来实现,
-
即使图像被缓存,解码仍然需要时间。
标签: javascript image google-chrome browser-cache http-caching