Search code examples
javascriptwordpressreplacetimerload

Hide an element and show another if page is taking too long to load


Is there a way to hide an element and then show another instead if the page is taking too long to fully load? Situation: I have a header with a background video, and if someone has a slow connection and the background video cannot load, then replace the header element with another header that has a static background image.

Thanks


Solution

  • 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