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?
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");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With