JavaScript: 如何检查图像或任何资产是否由浏览器存储而不是从互联网下载
JavaScript: How to check if image or any asset is stored by the browser and not downloaded from the internet
所以我正在使用 JavaScript 加载一些图像(又名设置图像 src),我正在加载时播放动画。
但问题是,如果浏览器已将其存储在客户端上,我不想播放它。为什么?因为很多图片会立即加载并同时进行动画处理,所以看起来真的 bad/annoying.
所以我会通过检测资产(图像)是否已经 downloaded/stored 或者是否需要更新资产来解决这个问题。这就是我卡住的地方。
示例:
CSS:
.AnimatedImage{
width: 100%;
max-width: 0px;
transition: max-width 0.2s;
transition-timing-function: cubic-bezier(0.68, 0.12, 0.32, 0.85);
}
JavaScript:
image.onload=function(){
if(imageClientStored(this)){
this.style.transition="";
this.style.max-width="100%";
}
else this.style.max-width="100%";
}
image.src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";
function imageClientStored(image){
??????????
}
是否有一张地图,其中存储的资产以 url 作为键或类似的东西排序?
如果它来自外部来源,则需要一些时间才能下载。查看它的加载时间,如果加载时间太长,那么它很可能不是本地的。
你可以在这里看到它在工作。第一次 运行 这个片段,它应该说 "from web",第二次它应该说 "from cache".
//expects
//string url
//function local (for callback)
//function download (for callback)
function loadImage(url,local,download){
var img = new Image();
var start = new Date();
img.onload = function(){
if((new Date)-start > 25){//25ms elapsed
download.call(img);//binds this to img in download callback
}else{
local.call(img);//binds this to img in local callback
}
};
img.src = url;
return img;
}
var testImg = loadImage(
"https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150",
function(){ console.log('from cache'); },
function(){ console.log('from web'); }
);
所以我正在使用 JavaScript 加载一些图像(又名设置图像 src),我正在加载时播放动画。
但问题是,如果浏览器已将其存储在客户端上,我不想播放它。为什么?因为很多图片会立即加载并同时进行动画处理,所以看起来真的 bad/annoying.
所以我会通过检测资产(图像)是否已经 downloaded/stored 或者是否需要更新资产来解决这个问题。这就是我卡住的地方。
示例:
CSS:
.AnimatedImage{
width: 100%;
max-width: 0px;
transition: max-width 0.2s;
transition-timing-function: cubic-bezier(0.68, 0.12, 0.32, 0.85);
}
JavaScript:
image.onload=function(){
if(imageClientStored(this)){
this.style.transition="";
this.style.max-width="100%";
}
else this.style.max-width="100%";
}
image.src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";
function imageClientStored(image){
??????????
}
是否有一张地图,其中存储的资产以 url 作为键或类似的东西排序?
如果它来自外部来源,则需要一些时间才能下载。查看它的加载时间,如果加载时间太长,那么它很可能不是本地的。
你可以在这里看到它在工作。第一次 运行 这个片段,它应该说 "from web",第二次它应该说 "from cache".
//expects
//string url
//function local (for callback)
//function download (for callback)
function loadImage(url,local,download){
var img = new Image();
var start = new Date();
img.onload = function(){
if((new Date)-start > 25){//25ms elapsed
download.call(img);//binds this to img in download callback
}else{
local.call(img);//binds this to img in local callback
}
};
img.src = url;
return img;
}
var testImg = loadImage(
"https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150",
function(){ console.log('from cache'); },
function(){ console.log('from web'); }
);