Over the past few years we’ve been seeing new audio, video, and image formats take shape to challenge the legacy formats that we’ve used since the web’s inception. This is a great development as we have more processing power and better compression algorithms have been developed, leading to faster load times and rendering. Hooray for speed!
The problem: as with every other feature added to the browser, some browsers get media format support faster than others, and some browsers refuse to support given formats. Simply put: we now need to do feature detection on media, something we’ve not traditionally had to do. A while back I posted about how you can detect WEBP support in the browser and now I’d like to show you how to detect supported video formats — it’s easier than you think!
canPlayType is the secret to detecting video format support in the browser. To use this method you must first create a <video> element instance:
const video = document.createElement('video');
You then call canPlayType, passing in the format’s MIME type and additional details as needed:
video.canPlayType(‘video/webm; codecs=”vp8, vorbis”‘); // “probably”