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

可紊 提交于 2019-12-04 08:50:27

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.

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