简体   繁体   中英

javascript check if image is in browser cache

I have the following code to check if an external image is cached or not

<script type="text/javascript">
    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()));         
</script>

I get the following result false false, then true false on firefox and IE (which I assume is that it first fires false false,then after it grabs the image, it fires true,false, but in chrome it is false, false always

any reason why?

The answer on this question seems to work on Chrome.

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

Answer copy/pasted from that question, not my work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM