如何检测图像加载失败,如果失败,尝试重新加载直到成功
How to detect image load failure and if fail, attempt reload until success?
我有一些图像从异地加载,无法控制它们的可用性。我发现,在重负载下,它们有时无法加载,但在快速刷新时,它们会立即显示出来。
有没有一种方法可以检测图像是否加载失败,如果是,则在img src上调用重载,直到加载为止?如果是,你能举一个例子吗?
<img onerror="dosomthing()" ...>
这里是我编译的一些可能会有所帮助的东西。我无法对此进行测试,如果您有任何问题,请告诉我。
$(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 Image Reloader
强制浏览器重新加载损坏的图像。对于存储在云中的图像(即AmazonS3),这是一个不错的解决方案。
为什么以及何时使用
当您从云(即Amazon S3)加载图像时,此插件是有效的,并且CDN会延迟到图像可访问为止。浏览器将显示一个损坏的图像图标,并且不会重试重新加载。jQuery image Reloader将处理此问题。
插件代码
激活插件所需的唯一代码是:
$(".slow-images").imageReloader();
相关文章:
- 当CDN加载失败时,为字体添加一个本地CSS回退
- 一旦第三方脚本加载失败,立即运行一段JavaScript
- 如何检查<对象>是否加载失败
- 在 RequireJS 中处理先决条件加载失败需要功能
- 如何检查选项卡加载失败
- iPhone img 加载失败
- 如何使用 AJAX 加载外部 javascript 文件并知道加载失败
- 如何检查外部javascript是否加载失败
- 角度模块加载失败
- 检查Javascript中图像和视频加载失败的正确方法
- Phonegap和requirejs动态脚本加载失败
- webpack reactjs应用程序加载失败:Uncaught ReferenceError:未定义snapapp
- 使用脚本标记检测Internet Explorer上的xml加载失败
- 如何检测图像加载失败,如果失败,尝试重新加载直到成功
- 为什么第一次加载失败,但后续加载有效
- 媒体源加载失败时没有错误事件
- Angular ng-view -加载失败
- Javascript /jquery:检测iframe页面加载失败
- 获取加载失败的网站的URL
- XHR加载失败:POST