How can I check if a background image is loaded?

后端 未结 10 1364
囚心锁ツ
囚心锁ツ 2020-11-22 07:05

I want to set a background image on the body tag, then run some code - like this:

$(\'body\').css(\'background-image\',\'http://picture.de/image.png\').load(         


        
10条回答
  •  孤街浪徒
    2020-11-22 07:41

    pure JS solution that will add preloader, set the background-image and then set it up for garbage collection along with it's event listener:

    Short version:

    const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
    let bgElement = document.querySelector("body");
    let preloaderImg = document.createElement("img");
    preloaderImg.src = imageUrl;
    
    preloaderImg.addEventListener('load', (event) => {
        bgElement.style.backgroundImage = `url(${imageUrl})`;
        preloaderImg = null;
    });

    A bit longer with nice opacity transition:

    const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
    let bgElement = document.querySelector(".bg-lazy");
    bgElement.classList.add("bg-loading");
    let preloaderImg = document.createElement("img");
    preloaderImg.src = imageUrl;
    
    preloaderImg.addEventListener('load', (event) => {
      bgElement.classList.remove("bg-loading");
      bgElement.style.backgroundImage = `url(${imageUrl})`;
      preloaderImg = null;
    });
    .bg-lazy {
      height: 100vh;
      width: 100vw;
      transition: opacity 1s ease-out;
    }
    
    .bg-loading {
      opacity: 0;
    }

提交回复
热议问题