Even though this approach incorporates JS, it fetches the initial image utilizing CSS, and will exclusively resort to JS for retrieving the alternative image if the primary image fails to load.
To begin, define the main image using CSS in the usual manner, like so:
.myImage {
background-image = "main-image.png";
}
Then, include the following JS code that kicks in only when the main image fails to load (otherwise, the fallback image won't be fetched).
var img = document.createElement("img");
img.onerror = function() {
var style = document.createElement('style');
style.innerHTML = '.myImage { background-image = url("http://fallback_image.png"); }';
document.head.appendChild(style);
}
img.src = "main_image.png";
Keep in mind that you can insert multiple rules into the CSS block appended through javascript, such as in cases where this needs to be done for multiple elements.