我一直在尝试找出是否使用 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/