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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7844982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:31:45  来源:igfitidea点击:

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

javascriptjqueryimagecross-browserimage-caching

提问by user979390

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:

我一直试图找出外部图像是否使用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>

It works perfectly on firefox but it always returns false on chrome.

它在 Firefox 上运行良好,但在 chrome 上总是返回 false。

Does someone has any idea how to make it work with chrome?

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

回答by Rob W

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/

我已经用纯 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

The first time, I get false and false. After I run the code again, I get true and false.

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



Using .completeand .height+ .widthgives 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 headersof your served image (Is Cache-controlpresent?). 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.

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

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

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