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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:29:58  来源:igfitidea点击:

how to check if an image was cached in js?

javascriptimagebrowser-cache

提问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 completeattribute of the Imageobject 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");