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

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.

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

Arne Hartherz 9 days ago