Read more

How to handle when an HTML <video> element cannot autoplay

Arne Hartherz
April 16, 2024Software engineer at makandra GmbH

HTML <video> elements can automatically start playing when the autoplay attribute is set on them. Except for when they can not, e.g. on pageload, or when the element enters the DOM without user interaction, or when the browser for some other reason decided to not start playing the video.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

While there is no native "autoplay failed" event to listen to, you can wait for video data to be loaded and then check if the video actually started playing.

Example

<video autoplay>
  <source src="example.mp4" type="video/mp4" />
</video>
const video = document.querySelector('video[autoplay]')

video.addEventListener('loadeddata', () => {
  if (video.paused) {
    // autoplay failed
  }
})

Note that this only works as long as the browser loads the video file. Current Chrome, Firefox, and Safari do that.
If you set preload="none", this will likely not work. If you set preload="metadata", you could listen to the loadedmetadata event.

Here is a codepen to try yourself: https://codepen.io/foobear/pen/yLrxPLq Show archive.org snapshot

Posted by Arne Hartherz to makandra dev (2024-04-16 14:37)