Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using image.complete to find if image is cached on chrome?

I have been trying to find out if an external image is cached on the browser with js, this is the code I have so far:

<html>
    <head></head>
    <body>

    <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

    <script>

        function cached( url ) {
            $("#imgx").attr({"src":url});
            if(document.getElementById("imgx").complete) {
                return true;
            } else {
                if( document.getElementById("imgx").width > 0 ) return true;
            }

            return false;
        }

    </script>

    <img id="imgx" src=""  />

    <script>

        $(document).ready(function(){
            alert(cached("http://www.google.com/images/srpr/nav_logo80.png"));
        });

    </script>

    </body>
</html>

It works perfectly on firefox but it always returns false on chrome.

Does someone has any idea how to make it work with chrome?

like image 206
user979390 Avatar asked Oct 21 '11 04:10

user979390


People also ask

How do I find cached images on a website?

Browser extensions can also access cached sites. Add Web Cache Viewer(Opens in a new window) to Chrome and right-click on any page to view the Google or Wayback Machine version of the web page.

How do I find cached photos?

Hold down the Alt (Option) key. You'll see the Library folder show up in the drop-down menu. Find the Caches folder and then your browser's folder to see all the cached files stored on your computer.

Does Google Chrome cache images?

Like other web browsers, Google Chrome features a cache that stores files such as images, scripts and video content from websites that you visit over time.


1 Answers

I've rewritten your code in plain JavaScript, to make it more independent on jQuery. The core functionality hasn't changed. Fiddle: http://jsfiddle.net/EmjQG/2/

function cached(url){
    var test = document.createElement("img");
    test.src = url;
    return test.complete || test.width+test.height > 0;
}
var base_url = "http://www.google.com/images/srpr/nav_logo80.png"
alert("Expected: true or false\n" +
      cached(base_url)
      + "\n\nExpected: false (cache-busting enabled)\n" +
      cached(base_url + "?" + new Date().getTime()));
//false = not cached, true = cached

The first time, I get false and false. After I run the code again, I get true and false.


Using .complete and .height + .width gives the expected results (FF 3.6.23, Chromium 14).

It's very likely that you've disabled the caching at your Chrome browser. If not, check the HTTP headers of your served image (Is Cache-control present?). This header exist at the Google sample

If you want to detect when an image has (not) finished loading, have a look at this question.

like image 134
Rob W Avatar answered Sep 23 '22 07:09

Rob W