jQuery 在将图像添加为背景图像之前检查图像是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14755183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:53:16  来源:igfitidea点击:

Checking if an image exists before adding it as a background image

jqueryapibackground-image

提问by spez86

There are a few solutions on stack regarding the use of .error() on images to determine if they exist and adding placeholders if they don't, but they all discuss its use strictly on <img>tags. Has anyone performed this type of validation to images that are not being added to <img>tags but rather as backgrounds on divs?

关于在图像上使用 .error() 来确定它们是否存在以及如果不存在则添加占位符的堆栈上有一些解决方案,但它们都严格讨论了它在<img>标签上的使用。有没有人对没有添加到<img>标签而是作为 div 背景的图像执行这种类型的验证?

We have a set of images coming in from a 3rd party API and there are cases where the entire set of image urls' that are returned do not exist. What would be the proper method in validating a set of images (destined to be background images) to determine if they exist and then apply proper placeholders if the validation(s) fails?

我们有一组来自第 3 方 API 的图像,并且在某些情况下,返回的整个图像 URL 集不存在。验证一组图像(注定是背景图像)以确定它们是否存在,然后在验证失败时应用适当的占位符的正确方法是什么?

回答by lolol

There is a few ways to do that:

有几种方法可以做到这一点:

Using ajax:

使用ajax:

$.ajax({
    url: "image.jpg",
    type: "HEAD",
    error: function () { alert("no image"); }
});

Using the javascript image object:

使用 javascript 图像对象:

var image = new Image(); 
image.src = "image.jpg";
if (image.width == 0) {
  alert("no image");
}

回答by eithed

Using jquery: $("<img src='[path]'>").load(function(){ [image exists!] });for every element that has your background-image.

使用 jquery:$("<img src='[path]'>").load(function(){ [image exists!] });对于每个具有background-image.

A solution we've implemented, is creating a intermediary, server-side script that checks if given image exists on the 3rd party API's side - if it does, serve the image, if not - serve a placeholder. This way an image is always served + adds additional functionality of caching / resizing of images.

我们实施的一个解决方案是创建一个中介服务器端脚本,用于检查给定的图像是否存在于 3rd 方 API 端——如果存在,则提供图像,如果不存在——则提供占位符。通过这种方式,始终提供图像 + 添加附加的图像缓存/调整大小功能。

Another solution is to actually not check if the image exists - you can provide placeholder image with CSS and if you're adding background-image via javascript then, if it exists, it will override an existing rule.

另一个解决方案是实际上不检查图像是否存在 - 您可以使用 CSS 提供占位符图像,如果您通过 javascript 添加背景图像,那么如果存在,它将覆盖现有规则。