By clicking on the button, the block is set to the background property as the background image. The background is loaded only after pressing the button. How to find out if the background is loaded and output this block?

    1 answer 1

    You can do it slyly.

    As such, there is no mechanism to track the loading of a picture when setting it as a background for a block. But what can we do?

    • Upload image by script
    • After downloading, use the same script to set it as a background (the picture is already loaded, it will be taken from the cache and there will not be a second request)

     function loadImage() { var src = 'https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/512/js.png'; // ссылка для ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ var img = document.createElement("img"); // создаСм абстрактноС ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ /* функция выполнится послС Π·Π°Π³Ρ€ΡƒΠ·ΠΊΠΈ ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ */ img.onload = function() { imgblock.style.background = "url(" + src + ")"; // устанавливаСм ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΡƒ ΠΊΠ°ΠΊ Ρ„ΠΎΠ½ }; /* Π²ΠΎΡ‚ Ρ‚ΡƒΡ‚ ΠΊΠ°ΠΊ Ρ€Π°Π· ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠ° Π½Π°Ρ‡Π½Π΅Ρ‚ Π·Π°Π³Ρ€ΡƒΠΆΠ°Ρ‚ΡŒΡΡ */ img.src = src; } 
     #imgblock { width: 100px; height: 100px; } 
     <div id='imgblock'></div> <button onclick="loadImage()">Клик</button>