2

Although there seems to be plenty of answers regarding broken <img> handling to show replacement images when the original could not be loaded, I can't seem to find a solution regarding missing background-images.

Question: How can I show another background-image if the original background-image was not loaded?

I apply the background-images like this:

<div style="background-image: url('img/test.jpg');"></div>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
  • The only solution I get is checking with JS if the ressource is available (using something like this : http://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript), and change the `div` property if it does not exist (or maybe check before setting the url). – Seblor Jul 28 '16 at 00:42
  • Or another solution, would be using, as url, a script redirecting the request to the image you want. With PHP, use something similar to this : `` (Of course, this is only a draft.) – Seblor Jul 28 '16 at 00:48

2 Answers2

0

You can use javascript to check the availability of the image.

var img = new Image();
img.src = 'img/test.jpg';
img.onload = function() {
    // create a script that will append style using background-image with this source
}

img.onerror = function() {
    // create a script that will append style using background-image with new source
}
ralcazar
  • 647
  • 5
  • 14
0

▶ 1st Option → JavaScript:

You can check if the image is available in JavaScript by sending an AJAX request as follows:

function isAvailable(url) {
    var xhttp = new XMLHttpRequest;
    xhttp.onreadystatechange = function() {
        return xhttp.status != 404;
    };
    xhttp.open('head', url, false);
    xhttp.send();
};

You can now use the above function to make the check and set the appropriate url:

var element = document.getElementById("element");
imgUrl = isAvailable("main-url") ? "main-url" : "backup-url";
element.style.backgroundImage = imgUrl;

▶ 2nd Option → PHP:

If you want to make the check server-side, then it gets a lot easier as you can use the native file_exists() function:

<?php
    $img_url = file_exists("main-url") ? "main-url" : "backup-url";
?>
<div style="background-image: url(<?php echo $img_url; ?>);"></div>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
  • Please be aware that the SO documentation link will become non-functional in the near future, which is why I made the edit removing the link. –  Sep 15 '17 at 16:45
  • Thanks for the tip @JoelGritter, I hadn't noticed that documentation is in the process of being dropped. I removed the link – Angel Politis Sep 18 '17 at 05:09