Home >Web Front-end >JS Tutorial >How to Dynamically Switch HTML5 Video Sources While Maintaining Browser Compatibility?

How to Dynamically Switch HTML5 Video Sources While Maintaining Browser Compatibility?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-14 15:02:02423browse

How to Dynamically Switch HTML5 Video Sources While Maintaining Browser Compatibility?

Dynamic Source Switching for HTML5 Video

Utilizing the HTML5 video element provides a versatile solution for video playback across various platforms. However, integrating a playlist or menu requires dynamically changing the video source. While naively updating the tags might seem straightforward, browser compatibility poses challenges.

Specifically, in Firefox, updating multiple tags using the load() method abruptly terminates the video player. Therefore, a more reliable approach is to exclusively employ the src attribute within the

Vanilla JavaScript Solution

To dynamically switch the video source, consider the following vanilla JavaScript snippet:

var video = document.getElementById('video');
var source = document.createElement('source');

source.setAttribute('src', 'video-url.mp4');
source.setAttribute('type', 'video/mp4');

video.appendChild(source);
video.play();

setTimeout(() => {
  video.pause();

  source.setAttribute('src', 'video-url.webm');
  source.setAttribute('type', 'video/webm');

  video.load();
  video.play();
}, 3000);

Compatibility Considerations

While the provided solution works well in Chrome, compatibility across other browsers should be verified. Additionally, consider incorporating browser-specific handling to ensure a consistent user experience.

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

Statement:
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