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

标签 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>

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

有人知道如何让它与 chrome 一起工作吗?

最佳答案

我已经用纯 JavaScript 重写了您的代码,使其更加独立于 jQuery。核心功能没有改变。 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

第一次,我得到了 false 和 false。再次运行代码后,我得到了 true 和 false


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

您很可能在 Chrome 浏览器中禁用了缓存。如果没有,请检查 HTTP headers您提供的图像(是否存在 Cache-control?)。 此 header 存在于 Google 示例中

如果您想检测图像何时完成(未)加载,请查看 this question .

关于javascript - 使用 image.complete 查找图像是否缓存在 chrome 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7844982/

相关文章:

javascript - 制作一个 &lt;input type ="text"/> 只有数字可以输入?

javascript - jQuery/JS 输入验证

javascript - 如何在javascript中为访问 token 生成oauth1签名?

javascript - 如何解决 "Cannot call method "addL"of undefined"

javascript - jQuery 动画不触发回调函数

jquery - 在 Columnizer jquery 中创建列规则

javascript - 如何将 javascript var 值传递给 Grails Controller ?

java - 我在哪里存储图像以便可执行 jar 文件可以访问它们?

jquery - 如何使用 jQuery 测量用户向下滚动了多远?

java - 缩放在 Java 中存储为 byte[] 的图像