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

前端 未结 1 1445
不知归路
不知归路 2020-12-01 19:52

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:


    

        
相关标签:
1条回答
  • 2020-12-01 20:13

    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.

    0 讨论(0)
提交回复
热议问题