Fallback background-image if default doesn't exist

后端 未结 5 725
忘掉有多难
忘掉有多难 2020-11-29 09:43

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

5条回答
  •  半阙折子戏
    2020-11-29 10:40

    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.

提交回复
热议问题