5

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?

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?

spez86
  • 732
  • 1
  • 11
  • 24

2 Answers2

25

There is a few ways to do that:

Using ajax:

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

Using the javascript image object:

var image = new Image(); 
image.src = "image.jpg";
if (image.width == 0) {
  alert("no image");
}
lolol
  • 4,287
  • 3
  • 35
  • 54
  • 1
    The JS solution you provided is perfect.. I can't believe I didn't think of the new Image() obj. I took what you have above and added it to a function. In case anyone wants to reference the solution above, I've created a fiddle using the above: http://jsfiddle.net/xHa7r/. Thanks for the quick response! – spez86 Feb 07 '13 at 16:15
  • @lolol This does not return a width or height, just the SRC. I think the image object needs to load before the system can access these properties. What a shame. It looks like such a neat solution... – Charles Robertson Aug 05 '17 at 16:43
1

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

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.

eithed
  • 3,933
  • 6
  • 40
  • 60