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
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.'); }
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!