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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)