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
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> |