I want to set an image as a background, however the image name might be either bg.png or bg.jpg.
Is there any non-javascript way to create
Although this solution does involve JS, it will download the first image using CSS, and will only use JS to download the fallback image if the main image failed to download.
First, set the main image with CSS as usual, for example:
.myImage {
background-image = "main-image.png";
}
And add the following JS that will only act if loading the main image fails (otherwise, fallback image will never be downloaded).
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";
Note that you can add multiple rules to the CSS block added with javascript, for example if you need to do this with multiple elements.