Getting StartedTutorialsPerformance & MetadataCreating a User Friendly Video Player

Creating a User Friendly Video Player

Adding video content to your website is an excellent way to engage with your users. This article will guide you in embedding videos on a web page the built in <video> HTML element.

The <video> Element

The <video> HTML element is a standard way to embed video content on a web page without using any external libraries or frameworks. It supports various video formats and provides built-in controls for playback, volume, and fullscreen mode, and has several configurable attributes to control how a video is displayed.

Here is a basic code example of an embedded video web player:

<video controls style="width: 100%; max-width: 1500px;">
  <source
    src="https://assets.imgix.net/videos/girl-reading-book-in-library.mp4?fm=mp4"
    type="video/mp4"
  />
 Your browser does not support embedded videos!
</video>

This will create the video below:

The controls attribute shows the user video controls. If the user’s browser does not support video, the text Your browser does not support embedded videos! will be displayed instead.

There are several other attributes that can be used to configure the <video> element. See the MDN docs for more information on video attributes.

Optimizing with Codec-Based Source Sets

You can optimize video delivery by as much as 34% by providing multiple codec options in a source set.

Modern hardware support different video codecs with varying levels of efficiency. You can see your own browser’s codec support by seeing the codec detector below:

Testing codec support...

By providing multiple video sources with different codecs, the browser will automatically select the most efficient format it supports. This allows you to deliver the same quality video at smaller file sizes to users with modern hardware while maintaining compatibility with older hardware.

Here’s how to set up a source set with multiple codec options with the <video> combined with the Video API’s video-codec parameter.

<video
  autoplay
  muted
  playsinline
  loop
  controls
  style="width: 100%; max-width: 1500px;"
  poster="https://assets.imgix.net/videos/girl-reading-book-in-library.mp4?fm=jpg&video-thumbnail=auto"
>
  <source
    src="https://assets.imgix.net/videos/girl-reading-book-in-library.mp4?fm=mp4&video-codec=av1"
    type="video/mp4; codecs=av01.0.05M.08"
  />
  <source
    src="https://assets.imgix.net/videos/girl-reading-book-in-library.mp4?fm=mp4&video-codec=h265"
    type="video/mp4; codecs=hev1.2.4.L120.B0"
  />
  <source
    src="https://assets.imgix.net/videos/girl-reading-book-in-library.mp4?fm=mp4&video-codec=h264"
    type="video/mp4"
  />
  Your browser does not support embedded videos!
</video>

This will create the following video player:

Click here to modify this in a Codepen.

The browser will evaluate each <source> element in order and play the first one it supports:

  1. AV1 (av01.0.05M.08) - The most efficient modern codec, providing the best quality-to-compression performance. Supported in recent versions of Chrome, Firefox, and Edge.
  2. H.265/HEVC (hev1.2.4.L120.B0) - A highly efficient codec that offers better compression than H.264, but not quite as much compression as AV1. Widely supported on Safari and newer versions of other browsers.
  3. H.264 (avc1.42E01E) - The most compatible codec, supported by virtually all browsers and devices. This serves as the fallback option.

When supported, the browser will choose AV1 for optimal performance since it can deliver the same quality video at a lower bitrate than either H.264 and H.265. If AV1 is not supported, it will fall back to H.265, which still offers better compression than H.264. If neither AV1 nor H.265 is supported, it will use H.264 to ensure compatibility.

Bitrate selection is dynamically applied by default when specifying fm=mp4 and when converting the codec, but you can also specify bitrates for each codec using the video-bitrate parameter if you want more control over the quality and file size of each source.

You can see the output filesize and bitrate from each file in the demo in the table below:

ParametersCodecBitrateFilesize
?fm=mp4&video-codec=av1AV12.4 Mbps6.5 MB
?fm=mp4&video-codec=h265H.2654.4 Mbps11.7 MB
?fm=mp4&video-codec=h264H.2649.8 Mbps25.9 MB

Detecting Codec Support with canPlayType()

While the <source> element approach works well for automatic codec selection, you may want to detect codec support programmatically using JavaScript - this can be done to take conditional action depending on the browser support.

The canPlayType() method allows you to check if a browser can play a specific media type and codec before loading the video.

The method returns three possible values:

  • "probably" - The browser is confident it can play this format
  • "maybe" - The browser might be able to play this format
  • "" (empty string) - The browser cannot play this format

Here’s how to detect support for different codecs:

const video = document.createElement('video')
 
// Check AV1 support
const av1Support = video.canPlayType('video/mp4; codecs=av01.0.05M.08')
console.log('AV1 support:', av1Support) // "probably", "maybe", or ""
 
// Check H.265/HEVC support
const h265Support = video.canPlayType('video/mp4; codecs=hev1.2.4.L120.B0')
console.log('H.265 support:', h265Support)
 
// Check H.264 support
const h264Support = video.canPlayType('video/mp4; codecs=avc1.42E01E')
console.log('H.264 support:', h264Support)

You can use this to programmatically select the best video source:

const video = document.querySelector('video')
const baseUrl = 'https://assets.imgix.net/videos/girl-reading-book-in-library.mp4'
 
// Create a temporary video element for testing
const testVideo = document.createElement('video')
 
// Determine the best supported codec
let videoUrl
if (testVideo.canPlayType('video/mp4; codecs=av01.0.05M.08')) {
  videoUrl = `${baseUrl}?fm=mp4&video-codec=av1`
  console.log('Using AV1 codec')
} else if (testVideo.canPlayType('video/mp4; codecs=hev1.2.4.L120.B0')) {
  videoUrl = `${baseUrl}?fm=mp4&video-codec=h265`
  console.log('Using H.265 codec')
} else {
  videoUrl = `${baseUrl}?fm=mp4&video-codec=h264`
  console.log('Using H.264 codec')
}
 
// Set the video source
video.src = videoUrl
video.load()

This approach is particularly useful when you need to:

  • Track which codecs your users’ browsers support for analytics
  • Make decisions about video delivery before the video element is created
  • Provide user feedback about their browser’s capabilities
  • Conditionally load different video players or libraries based on codec support

Setting up Autoplay

Warning

Autoplay is never guaranteed to work for every user or every browser.

Automatically playing videos can be a great way to get users to interact with your content. At the same time, it can be detrimental to the user experience to play videos automatically each time they open up your app or webpage.

All browser vendors (such as Chrome and Safari) have different policies and algorithms that determine whether or not a video will be allowed to play automatically. The requirements vary between browsers, but these are the general conditions that will give your videos a better chance of being autoplayed:

  • Your video element is muted with the muted attribute
  • The user has clicked anywhere on the page
  • (Chrome - desktop) The user’s Media Engagement Index scores over a certain threshold
  • (Chrome - mobile) The user has added the site to their home screen
  • (Safari) The device is not in power-saving mode

If autoplay is not allowed, the user must click the video to initiate playback.

Using the autoplay attribute

The autoplay attribute is the most common and easiest way to enable autoplay for a video. Here’s a full HTML example you can copy and paste, including other attributes for styling the video. The video may or may not autoplay, depending on your browser:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
 
<video
  id="my-autoplay-player"
  autoplay
  controls
  loop="loop"
  muted="muted"
  style="width: 100%; max-width: 1500px;"
  crossorigin="anonymous"
>
  <script>
    const video = document.querySelector("#my-autoplay-player")
    const src =
      "https://assets.imgix.net/videos/girl-reading-book-in-library.mp4?fm=hls"
    if (video.canPlayType("application/vnd.apple.mpegurl")) {
 video.src = src
    } else if (Hls.isSupported()) {
      const hls = new Hls()
 hls.loadSource(src)
 hls.attachMedia(video)
    } else {
 console.error(
        "This is a legacy browser that doesn't support Media Source Extensions",
 )
    }
  </script>
</video>

This will create the video player below:

Click here to modify this in a Codepen.

While this is the easiest method for enabling autoplay, it’s not the best. The autoplay attribute only tells the browser what the video should do, but it does not define or log any fallback behavior for a video element.

This is not a problem most of the time since it will fall back to requiring input from a user to start playback. However, in cases such as a background video, you would instead want to define a fallback behavior that would not require user input, such as showing a background image. You can use Javascript to initiate autoplay instead of the autoplay attribute.

Using video.play()

If Javascript is enabled, use the video.play() method to play the video instead of using a video attribute.

Here’s a code example showing how to use video.play():

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video
  id="my-player"
  controls="controls"
  style="width: 100%; max-width: 1500px;"
  crossorigin="anonymous"
/>
<script>
  let video = document.querySelector("#my-player")
  let src =
    "https://assets.imgix.net/videos/girl-reading-book-in-library.mp4?fm=hls"
 
  if (video.canPlayType("application/vnd.apple.mpegurl")) {
 video.src = src
  } else if (Hls.isSupported()) {
    let hls = new Hls()
 
 hls.loadSource(src)
 hls.attachMedia(video)
  } else {
 console.error(
      "This is a legacy browser that doesn't support Media Source Extensions",
 )
  }
 video
    .play()
    .then(function () {
      // autoplay was successful!
    })
    .catch(function (error) {
      // do something if you want to handle or track this error});
    })
</script>

This will create the video player below:

Click here to modify this in a Codepen.

Assuming the intention is to create a background video, the code above will automatically play a video if autoplay is allowed. If is not, we can use the .catch() function to log an autoplay error or to swap out the <video> element for an <image> element instead.

When to use autoplay

Autoplay’s primary use case is immediately grabbing a user’s attention on a web page. It can also save the user a click as long as the content is relevant to the user.

However, autoplay can also create a negative user experience and hurt user engagement by creating too much website noise.

With that in mind, autoplay should be used in the following scenarios:

  • To create a background video as part of your design composition
  • To enrich the user experience by automatically playing a video they were guaranteed to click
  • To play a video that is immediately visible to the user when the page loads
  • To play a video that is critical for the user to watch

When using autoplay, you should avoid the following:

  • You should not autoplay videos below the fold
  • You should not autoplay videos that the user cannot see
  • You should not autoplay multiple videos at a time