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

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

本文关键字:缓存 存在 chrome 是否 图像 image complete 查找 使用      更新时间:2023-09-26

我一直在试图找出外部图像是否缓存在浏览器上与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。核心功能没有改变。小提琴: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 and false。再次运行代码后,我得到true and false


使用.complete.height + .width得到预期结果(FF 3.6.23, Chromium 14)。

很可能你已经禁用了Chrome浏览器的缓存。如果没有,检查所提供图像的HTTP头(Cache-control是否存在?)。这个标题存在于Google示例

如果你想检测一个图像何时完成加载,看看这个问题。