HTML5 video autoplay but with a 5 seconds of delay

Viewed 62192

I have a 20 second long HTML5 video loop as the background on my webpage and it is set to autostart. Is it possible to delay the video autoplay for 5 seconds? I am trying to allow the video to load completely before trying to play to prevent it from stuttering as much. Here is my current code:

<video id="video_background" poster="images/dmm_background.jpg" controls="controls" preload="true" autoplay="true" loop="loop" muted="muted" volume="0"> 
<source src="videos/backgroundvideo.mp4" type="video/mp4"> 
<source src="videos/backgroundvideo.webm" type="video/webm">
</video>
</video>

Any help is greatly appreciated!!

2 Answers

That would be better to remove autoplay attribute from video tag and add it when you actually need it (meaning in 5 seconds). And if you are willing to preload video, then you should use preload="auto" (not preload="true"), it will load completely while loading a page.

const startVideo = async () => {
  const video = document.querySelector('#video_background');

  try {
      await video.play();

      video.setAttribute('autoplay', true);

      console.log('video started playing successfully');
  } catch (err) {
    console.log(err, 'video play error');
    // do stuff in case your video is unavailable to play/autoplay
  }
}

setTimeout(startVideo, 5000)
Related