javascript – 如何检测图像加载失败,如果失败,尝试重新加载直到成功?

前端之家收集整理的这篇文章主要介绍了javascript – 如何检测图像加载失败,如果失败,尝试重新加载直到成功?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@我有一些图像从非现场加载,无法控制它们的可用性.我发现,在很大的负载下,它们有时无法加载,但是在快速刷新时,它们会显示出来.

有没有办法检测图像是否无法加载,如果是这样,请在img src上重新加载,直到加载?如果是的话,请提供一个例子?

解决方法

这里编译的东西可能有帮助.我无法设法做这个测试,请让我知道如果你有任何问题.
  1. $(function() {
  2. var $images = $('img.imageClassUpdateAtInterval:not([src="/assets/spinner.gif"])');
  3.  
  4. // Now,no such image with
  5. // a spinner
  6. if($images.length === 0 && window.imageLocator)
  7. clearInterval(window.imageLocator);
  8.  
  9.  
  10. window.imageLocator = setInterval(function() {
  11. $images.each(function() {
  12. $this = $(this);
  13. if (!$this.data('src')) {
  14. $this.data('src',$this.prop('src'));
  15. }
  16.  
  17. $this.prop('src',$this.data('src') + '?timestamp=' + new Date().getTime());
  18. console.log($this.prop('src'));
  19. });
  20. },60 * 1000);
  21.  
  22. // suppose,an error occured during
  23. // locating the src (source) of the
  24. // image - image not found,network
  25. // unable to locate the resource etc.
  26. // it will fall in each time on error
  27. // occurred
  28. $('img.imageClassUpdateAtInterval').error(
  29. function () {
  30. // set a broken image
  31. $(this).unbind("error").attr("src","/assets/broken.gif");
  32. // setting this up in relative
  33. // position
  34. $(this).css("position","relative");
  35. $(this).apppend("<span>Error occured</span>");
  36. $(this).find("span").css({"position": "absolute","background-color": "#252525","padding": ".3em","bottom": "0"});
  37. });
  38.  
  39. });

上述解决方案是由@user113716@travis开始的两种不同的解决方案编制而成

猜你在找的JavaScript相关文章