我一直试图找出外部图像是否用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/ 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
.
Using .complete
and .height
+ .width
gives the expected results (FF 3.6.23, Chromium 14).
您很可能已禁用 Chrome 浏览器的缓存。如果没有,请检查HTTP 标头 https://stackoverflow.com/questions/6116274/http-headers-cache-question您所提供的图像的(是Cache-control
展示?)。此标头存在于 Google 示例中
如果您想检测图像何时完成(未)加载,请查看这个问题 https://stackoverflow.com/questions/7718430/run-a-function-each-time-an-images-has-finished-loading/7718503#7718503.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)