Hello everyone, How to make background-image load before the page is displayed?

Htl

<div class="background"></div> 

CSS

 .background { background-image: url(img/background.png); } 

    1 answer 1

    It’s difficult to do this yourself (as I understood when I was looking for a solution myself).
    Found such a script . It allows you to execute the script after downloading an image from the background, for example, using such a code (jQuery):

     $('#container').imagesLoaded( { background: true }, function() { console.log('Π‘Π΅ΠΊ-изобраТСния Π·Π°Π³Ρ€ΡƒΠΆΠ΅Π½Ρ‹!'); }); 

    But I, while using it, faced the fact that it does not initialize the backgrounds of pseudo-elements and does not track their loading (even using the DOM readiness function). It is necessary to know, I think.

    • Thanks for the answer, I will try now! - Ruslan Liashenka
    • @harbor, keep anchor link to github: github.com/desandro/imagesloaded#background - VostokSisters
    • I can't figure something out, I connected <script src="https://unpkg.com/imagesloaded@4.1/imagesloaded.pkgd.min.js"></script> <!-- or --> <script src="https://unpkg.com/imagesloaded@4.1/imagesloaded.pkgd.js"></script> added $('#background').imagesLoaded( { background: true }, function() { console.log('Π‘Π΅ΠΊ-изобраТСния Π·Π°Π³Ρ€ΡƒΠΆΠ΅Π½Ρ‹!'); }); all right if yes, then you can still see how the image is loading, I hope I was mistaken somewhere .. - Ruslan Liashenka
    • @harbor, do you understand what this code does? It displays in the browser console (In chrome, this is Ctrl + Shift + J) the message Π‘Π΅ΠΊ-изобраТСния Π·Π°Π³Ρ€ΡƒΠΆΠ΅Π½Ρ‹! when the picture is fully loaded. Right? Or he does not display it when they have already loaded? Because then something is wrong, and it is strange. - VostokSisters
    • @harbor, so that the loading background cannot be seen from the element, while it is actually loading, you can hide this block. And to show when the picture is already loaded, that is, to add $('#background').css('display', 'block') instead of the console output from my example, for example. - VostokSisters