javascript 如何检查图像是否已缓存在 js 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15352803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to check if an image was cached in js?
提问by looping
when I joined an interview , I was asked the question, I didn't know how to answer it .
我参加面试的时候被问到这个问题,我不知道怎么回答。
do you know the key point of the question?
你知道问题的关键点吗?
回答by Blender
Check if the complete
attribute of the Image
object is true
:
检查对象的complete
属性Image
是否为true
:
function is_cached(src) {
var image = new Image();
image.src = src;
return image.complete;
}
It seems to work (although it'll load the image if it isn't in the cache, which might not be what you want):
它似乎有效(尽管它会加载不在缓存中的图像,这可能不是您想要的):
> is_cached('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3')
false
> is_cached('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3')
true
回答by Sudhir Bastakoti
you could check like:
你可以像这样检查:
function is_cached(img_url){
var imgEle = document.createElement("img");
imgEle.src = img_url;
return imgEle.complete || (imgEle.width+imgEle.height) > 0;
}
//and check, returns true or false depending on cached or not
is_cached("http://www.somesite.com/some_image.jpg");