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

左心房为你撑大大i 提交于 2019-12-21 17:23:09

问题


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?


回答1:


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");
}



回答2:


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.



来源:https://stackoverflow.com/questions/14755183/checking-if-an-image-exists-before-adding-it-as-a-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!