【发布时间】:2012-01-23 07:56:49
【问题描述】:
我从异地加载了一些图像,无法控制它们的可用性。我发现在重负载下它们有时会无法加载,但在快速刷新时它们会立即显示出来。
有没有办法检测图像是否加载失败,如果是,则在 img src 上重新加载,直到加载?如果有,能否举个例子?
【问题讨论】:
标签: javascript jquery html ruby-on-rails css
我从异地加载了一些图像,无法控制它们的可用性。我发现在重负载下它们有时会无法加载,但在快速刷新时它们会立即显示出来。
有没有办法检测图像是否加载失败,如果是,则在 img src 上重新加载,直到加载?如果有,能否举个例子?
【问题讨论】:
标签: javascript jquery html ruby-on-rails css
<img onerror="dosomthing()" ...>
【讨论】:
$('#myImg').bind('error', function(e){ ... }); :)
img 的src 更改为默认资源:类似于:$('#img1').attr('src','images/no-profile-photo.png')。或者按照您的建议,重新尝试加载相同图像的逻辑代码。
这是我编译的可能有帮助的东西。我无法对此进行测试,如果您有任何问题,请告诉我。
$(function() {
var $images = $('img.imageClassUpdateAtInterval:not([src="/assets/spinner.gif"])');
// Now, no such image with
// a spinner
if($images.length === 0 && window.imageLocator)
clearInterval(window.imageLocator);
window.imageLocator = setInterval(function() {
$images.each(function() {
$this = $(this);
if (!$this.data('src')) {
$this.data('src', $this.prop('src'));
}
$this.prop('src', $this.data('src') + '?timestamp=' + new Date().getTime());
console.log($this.prop('src'));
});
}, 60 * 1000);
// suppose, an error occured during
// locating the src (source) of the
// image - image not found, network
// unable to locate the resource etc.
// it will fall in each time on error
// occurred
$('img.imageClassUpdateAtInterval').error(
function () {
// set a broken image
$(this).unbind("error").attr("src", "/assets/broken.gif");
// setting this up in relative
// position
$(this).css("position", "relative");
$(this).apppend("<span>Error occured</span>");
$(this).find("span").css({"position": "absolute", "background-color": "#252525", "padding": ".3em", "bottom": "0"});
});
});
上面的解决方案是由@user113716和@travis开始的两个不同的解决方案编译而成的
【讨论】:
看看这段代码:
$('img.autoFix').error(function(){
var src = this.src;
this.src = src.substr(0, src.indexOf('?')) + '?t=' + new Date().getTime()
});
【讨论】:
将其他答案的一些想法与我自己的想法混合在一起后,我想出了一些对我有用的东西:
将此添加到您的 img 元素中:
onerror="tryAgain(this)"
脚本:
<script>
function tryAgain(e)
{
setTimeout(reloadImg, 1000, e);
}
function reloadImg(e)
{
var source = e.src;
e.src = source;
}
</script>
您当然可以将超时更改为您想要的任何值。 (请原谅我在回答中没有使用 $;我是 JS 新手,根本没有使用过 JQuery)。
【讨论】:
这是一种处理页面上所有图像的非常简单的方法。
https://github.com/doomhz/jQuery-Image-Reloader
jQuery 图像重新加载器
强制浏览器重试加载损坏的图像。存储在云(即 Amazon S3)中的图像的一个不错的解决方案。
为什么以及何时使用它?
当您从云(即 Amazon S3)加载图像并且 CDN 有延迟直到图像可访问时,此插件才有效。浏览器将显示一个损坏的图像图标,并且不会重试重新加载它。 jQuery Image Reloader 会解决这个问题。
插件代码
激活插件所需的唯一代码是:
$(".slow-images").imageReloader();
【讨论】: