Search code examples
javascriptspinnerloading

Display spinner until page loads with external resources


I want to display a spinner until the page is fully loaded including the external resources. The page is showing banners (ads) and it is loading these banners and ads from the ad server.

I am using the following logic to display the spinner and hide it once the transition ends, however, I think it is not checking if all page resources are loaded:

HTML

<div class="loader"></div>

CSS

.loader {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #333333;
  transition: opacity 0.75s, visibility 0.75s;
}

.loader--hidden {
  opacity: 0;
  visibility: hidden;
}

.loader::after {
  content: "";
  width: 75px;
  height: 75px;
  border: 15px solid #dddddd;
  border-top-color: #009578;
  border-radius: 50%;
  animation: loading 0.75s ease infinite;
}

@keyframes loading {
  from {
    transform: rotate(0turn);
  }
  to {
    transform: rotate(1turn);
  }
}

JS

window.addEventListener("load", () => {
  const loader = document.querySelector(".loader");

  loader.classList.add("loader--hidden");

  loader.addEventListener("transitionend", () => {
    document.body.removeChild(loader);
  });
});

I tried to implement this code.


Solution

  • One way to go about it is to check if the div is empty or not (empty means loading, and not empty means stop loading).

    You can achieve this using JavaScript childNodes (read more here). However, you have to consider what happens when the request fails and the third-party element doesn't load to the div.