Skip to content Skip to sidebar Skip to footer

How To Check If An Image Was Cached In Js?

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?

Solution 1:

Check if the complete attribute of the Image object is true:

functionis_cached(src) {
    var image = newImage();
    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

Solution 2:

you could check like:

functionis_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 notis_cached("http://www.somesite.com/some_image.jpg");

Post a Comment for "How To Check If An Image Was Cached In Js?"