Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 980
spez86 Avatar asked Feb 07 '13 15:02

spez86


2 Answers

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");
}
like image 146
lolol Avatar answered Oct 11 '22 02:10

lolol


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.

like image 26
eithed Avatar answered Oct 11 '22 01:10

eithed