When attempting to dynamically change video sources in an HTML5
To overcome this problem, consider the following approach that uses the canPlayType() function:
const video = document.getElementById('video'); function changeSource(newUrl) { // Remove existing `<source>` tags while (video.children.length > 0) { video.removeChild(video.children[0]); } // Create a new `<source>` tag with the new URL const source = document.createElement('source'); source.src = newUrl; // Determine the appropriate MIME type using `canPlayType()` const mimeType = video.canPlayType('video/mp4') ? 'video/mp4' : 'video/webm'; source.type = mimeType; // Append the new `<source>` tag to the video element video.appendChild(source); // Reload the video video.load(); video.play(); }
This solution involves removing existing
The above is the detailed content of How to Dynamically Change Video Sources in HTML5 without Browser Compatibility Issues?. For more information, please follow other related articles on the PHP Chinese website!