我的网站中有一个很大的背景图片,有时背景图片无法加载。
它在控制台中显示此错误:
GET http://www.mywebsite.com/wp-content/uploads/2017/01/cover_background.jpg 404 (Not Found)
如果我右键单击链接并“在新选项卡中打开”,或刷新页面,图像将正确显示。
这似乎是服务器端的某种资源请求错误,对吗?
我想在 jQuery 中找到一种方法:
- 检查图像是否正确加载
- 如果没有,请单独重新加载该图像
PS:我见过一些用于获取图像 header 并检查它是否返回 200 或 404 的 AJAX 方法,但我认为这不适用于我的情况,因为该 AJAX 调用将是对服务器的另一个请求,并且服务器可能会向 AJAX 返回 200 状态,即使它在加载页面时返回 404。
PS 2:它不重复。那是生的。这是最终产品。在该问题中,它没有指定您需要在错误时设置不同的镜像(备份镜像)。它只是再次引用同一张图像。
最佳答案
感谢@Snowmonkey,我找到了解决方案:
$("img#background").on('error', function() {
// Backup image in case of error
$("img#background").attr('src', 'http://www.mywebsite.esp.br/wp-content/uploads/2017/01/fundo-1366-768-1.jpg');
})
这是我在网站中使用的最终版本。它不仅检查图像是否正确加载并修复它,而且还为较小的屏幕加载较小的图像,从而使网站更快:
// Background image for resolutions between 600px and 1500px
if ($(window).width() > 600 && $(window).width() < 1500) {
// First we set a background image
$("img#background").attr('src', 'http://www.mywebsite.esp.br/wp-content/uploads/2017/01/fundo-1366-768.jpg');
// Then we check if it returned an error
$("img#background").on('error', function() {
// If it did, we set a "backup" image. In this case, an exact copy of the original
$("img#background").attr('src', 'http://www.mywebsite.esp.br/wp-content/uploads/2017/01/fundo-1366-768-1.jpg');
})
// Background image for resolutions higher than 1500px
} else if ($(window).width() > 1500) {
// Same process as above, but with a different src
$("img#background").attr('src', 'http://www.mywebsite.esp.br/wp-content/uploads/2017/01/fundo-1920-1080.jpg');
$("img#background").on('error', function() {
$("img#background").attr('src', 'http://www.mywebsite.esp.br/wp-content/uploads/2017/01/fundo-1920-1080-1.jpg');
})
}
关于javascript - 有时图像无法加载并出现 404 错误 - 如何使用 jQuery 解决此问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41941387/