使用 image.complete 查找图像是否缓存在 chrome 上?
我一直试图找出外部图像是否用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 一起工作吗?
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:
<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.
Does someone has any idea how to make it work with chrome?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我用纯 JavaScript 重写了您的代码,使其更加独立于 jQuery。核心功能没有改变。
小提琴:http://jsfiddle.net/EmjQG/2/
第一次,我得到
假和假
。再次运行代码后,我得到true 和 false
。Using
.complete
and.height
+.width
gives the expected results (FF 3.6.23, Chromium 14).您很可能已禁用 Chrome 浏览器的缓存。如果没有,请检查所提供图像的 HTTP 标头(是
Cache-control< /code> 存在?)。 Google 示例中存在此标头
如果您想检测图像何时(未)完成加载,请查看 这个问题。
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/
The first time, I get
false and false
. After I run the code again, I gettrue and false
.Using
.complete
and.height
+.width
gives 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 headers of your served image (Is
Cache-control
present?). This header exist at the Google sampleIf you want to detect when an image has (not) finished loading, have a look at this question.