JavaScript:如何在不附加查询字符串的情况下重试加载图像? [英] JavaScript: how to retry loading an image without appending query string?

查看:96
本文介绍了JavaScript:如何在不附加查询字符串的情况下重试加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个网页包含很少的图像,平均大小为5-10.

A webpage contains few images, 5-10, average size.

有时,图像加载失败,并且不显示.

Sometimes, randomly, the loading of an image fails and it is not displayed.

让我们说每100张加载的图像中有1张失败.

Let say that every 100 images loaded 1 fails.

可能由于服务器繁忙或任何临时网络问题而发生.

That may happen because the server is busy or there is a temporary network problem, any reason..

我肯定知道获取图像的请求是有效的,因此,如果我尝试重新加载图像,则很有机会获得它.

I know for sure that the request to obtain the image is valid so if I retry to load the image I have very good chances to get it.

我有代码来检测图像何时无法加载并触发回调.

I have code to detect when an image fails to load and trigger a callback.

但是,然后如何告诉浏览器尝试加载该图像" ?

But then, how can I tell the browser "retry loading that image" ?

我可以只从DOM中删除图像,然后再放回去吗?

Can I just remove the image from the DOM and put it back again?

如果我在URL后面附加一个随机查询字符串,则可以肯定会重新加载图片,但我宁愿避免,因为图片不会被正确缓存.

If I append to the URL a random query string the image will be reloaded for sure but I'd prefer to avoid that because the image won't be properly cached.

我使用的是jQuery,所以jQuery解决方案对我来说就像纯JavaScript一样.

I'm using jQuery, so a jQuery solution is good for me as pure JavaScript.

推荐答案

您可以做的就是尝试将图像加载到新的Image对象中.如果加载了图像,它将同时更新所有其他位置(类似于您将同一图像嵌入50次的方式,一旦加载一次,它们都会全部显示).因此,在您的回调中(我认为这是一个错误回调),只需尝试:

What you can do is just try to load the image in a new Image object. If an image loads, it will update all other places as well (similar to how if you embed the same image 50 times, once it loads once, they all show). So, in your callback (which I assume is an error callback), just try:

var img = new Image();
img.src = this.src; // this should refer to the original failed image

这将触发在新的图像对象中加载相同的URL.如果可行,那么两者都将被更新,而我们刚刚创建的内容将永远不会显示在任何地方.

That'll trigger the loading of that same URL in the new image object. If it works, both will be updated and the one we just created is simply never shown anywhere.

这篇关于JavaScript:如何在不附加查询字符串的情况下重试加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆