使用image.complete来查找图像是否缓存在chrome上?

use*_*390 7 javascript jquery image cross-browser image-caching

我一直试图找出一个外部图像是否在js上缓存在浏览器上,这是我到目前为止的代码:

<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>
Run Code Online (Sandbox Code Playgroud)

它在firefox上完美运行,但它总是在chrome上返回false.

有人知道如何使用chrome吗?

Rob*_*b W 14

我用简单的JavaScript重写了你的代码,使它更加独立于jQuery.核心功能没有改变. 小提琴: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
Run Code Online (Sandbox Code Playgroud)

我第一次得到false and false.在我再次运行代码后,我得到了true and false.


使用.complete.height+ .width给出预期结果(FF 3.6.23,Chromium 14).

您很可能已在Chrome浏览器中停用了缓存功能.如果没有,请检查所提供图像的HTTP标头(是否Cache-control存在?).此标题存在于Google示例中

如果要检测图像何时(未)完成加载,请查看此问题.