Home > Web Front-end > JS Tutorial > body text

How to Dynamically Change a Video Source in HTML5 While Maintaining Browser Compatibility?

Mary-Kate Olsen
Release: 2024-11-14 22:48:02
Original
359 people have browsed it

How to Dynamically Change a Video Source in HTML5 While Maintaining Browser Compatibility?

Dynamically Changing the Video Source in HTML5

In the pursuit of creating a universal video player, it is crucial to consider browser compatibility when dynamically changing the video source.

The Problem

Using multiple tags within a

Solution

To overcome this issue, it is recommended to use a single src attribute within the

Example Implementation

The following JavaScript code demonstrates the process of dynamically changing the video source using the src attribute and canPlayType() function:

var video = document.getElementById('video');
var source = document.createElement('source');
var supported = video.canPlayType('video/mp4');
if (supported == '' || supported == 'no') {
  supported = video.canPlayType('video/webm');
}
if (supported != '' && supported != 'no') {
  source.setAttribute('src', 'path/to/video.' + supported.replace('video/', ''));
  source.setAttribute('type', supported);
  video.appendChild(source);
  video.load();
  video.play();
} else {
  alert('Video file not supported.');
}
Copy after login

This approach simplifies the source-changing process, ensures cross-browser compatibility, and provides a consistent video playback experience.

The above is the detailed content of How to Dynamically Change a Video Source in HTML5 While Maintaining Browser Compatibility?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template