由於各家瀏覽器對 HTML5 的支援程度不一,在開發時往往需要事先偵測使用者環境是否具備播放能力。以下這段簡短的 JavaScript 透過建立 video 元素並檢查其 canPlayType 屬性,即可判斷瀏覽器是否理解 video 標籤:
// Check if the browser understands the video element.
function understands_video() {
return !!document.createElement('video').canPlayType; // boolean
}
if ( !understands_video() ) {
// Must be older browser or IE.
// Maybe do something like hide custom
// HTML5 controls. Or whatever...
videoControls.style.display = 'none';
}
若偵測結果為不支援,就能進一步隱藏自訂的 HTML5 播放控制項,或改為提供替代方案,確保舊版瀏覽器使用者也能順暢瀏覽。