Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 889
looping Avatar asked Mar 12 '13 03:03

looping


People also ask

How do I know if my browser has cached images?

Show the Browser Cache In Chrome, we can go to chrome://cache to view the contents of the cache. This will display a page of links to a detailed view for each cached file.

How do you check if JS is cached?

If you have Chrome, open the Inspector (right-click, "Inspect Element"), then click the Network tab. Now reload the page. You should see a list of all of the elements that were loaded for the page. To determine if the Javascript (or any element) was cached, what you want to look for is the "Size" column.

Can JavaScript read cache?

There is no way to read the cache manually - it all happens behind the scenes, if there is cache. Yes, you can store the website's source code to the browser cache, but only the client-side part - HTML/CSS/JS/images/fonts/etc.

What is JavaScript caching?

Code caching (also known as bytecode caching) is an important optimization in browsers. It reduces the start-up time of commonly visited websites by caching the result of parsing + compilation.


2 Answers

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
like image 136
Blender Avatar answered Sep 21 '22 04:09

Blender


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");
like image 21
Sudhir Bastakoti Avatar answered Sep 22 '22 04:09

Sudhir Bastakoti