how to check if an image was cached in js? [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-18 02:52:27

问题


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?


回答1:


Check if the complete attribute of the Image object is 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



回答2:


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");


来源:https://stackoverflow.com/questions/15352803/how-to-check-if-an-image-was-cached-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!