[Solved] Hide an element and show another if page is taking too long to load [closed]


It’s not something I’d usually recommend but here’s a pretty hacky solution.

const video = document.querySelector("#video-element-id");

let tooSlow = false;

let timeout = setTimeout(() => {
  tooSlow = true;
  
  ...logic to change header

  clearTimeout(timeout);
}, 1000);

video.addEventListener('loadeddata', () => {
  console.log(tooSlow ? 'too slow' : 'loaded');
  clearTimeout(timeout);
});

* EDIT – or you could do the same with a promise tbf

const video = document.querySelector("#video-element-id");

const loader = new Promise((resolve) => {
  let timeout = setTimeout(() => {
      resolve(false);
    }, 0);

  video.addEventListener('loadeddata', () => {
      resolve(true);
    });
});

loader
  .then((isLoaded) => {
    if (isLoaded) {
      console.log('loaded');
      
      return;
    }
    
    console.log('too slow');

    ...logic to change header
  });

There’s still the issue that the video will continue to download even after the header has been switched though. A better solution might be to use the poster attribute to show a still image of the video until it’s finished loading 🙂 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-poster

solved Hide an element and show another if page is taking too long to load [closed]