Home > Article > Web Front-end > How to Dynamically Change the Source of an HTML5 Video Tag?
Changing the Source of an HTML5 Video Tag: A Comprehensive Solution
Creating a universal video player requires addressing the issue of dynamically changing the source of the video. This allows users to switch between videos in a playlist. While previous approaches using multiple
Identifying the File Type Using canPlayType():
To determine the appropriate file type for the video, we can utilize the canPlayType() function. This function returns a string indicating the browser's level of support for a given media type. For example:
var canPlayMP4 = video.canPlayType('video/mp4'); var canPlayWebM = video.canPlayType('video/webm');
Based on the results of canPlayType(), we can dynamically set the src attribute of the
Implementation Using Vanilla JavaScript:
Here's a code snippet demonstrating how to change the source of the video using vanilla JavaScript:
var video = document.getElementById('video'); // Create a new source element var source = document.createElement('source'); // Set the source attributes dynamically based on browser support if (canPlayMP4) { source.setAttribute('src', 'video.mp4'); source.setAttribute('type', 'video/mp4'); } else if (canPlayWebM) { source.setAttribute('src', 'video.webm'); source.setAttribute('type', 'video/webm'); } // Append the source to the video element video.appendChild(source); // Play the video video.play();
This approach allows for dynamic source switching without the drawbacks of using multiple
The above is the detailed content of How to Dynamically Change the Source of an HTML5 Video Tag?. For more information, please follow other related articles on the PHP Chinese website!