How to write a feature detection script in JavaScript


When I use a HTML5 feature in my website I will often test the browser that is visiting to see if it is capable of using the feature. If it is not capable I will Fall-back to something that the browser is a capable of supporting. In practice, I use modernizr for this purpose, however, there maybe instances where you want to write your own tests.

In most instances writing these feature detection tests is quite straight forward.

The example below tests to see if a browser is capable of supporting HTML5 Audio.

return !!document.createElement('audio').canPlayType;

If the browser is able to create the audio element and the canPlayType property is true, this test will return true. If the browser is unable to create the audio element the test will fail.

Mark Pilgrim has a great resource that shows you how to test almost any  HTML5 feature.

To use the code above I might create my own little library and call it myTests. I add the property audio and assign a self executing function (this basically means that the function runs as soon as it is created) and then the returned value is saved into the variable audio.

  var myTests = {
            audio: (function () {
                return !!document.createElement('audio').canPlayType;
            }())
        }

To test audio I can then just call

myTests.audio

So for example the following code would use my test when the browser loads:

 window.onload = function () {
            if (myTests.audio) {
                alert("Your browser supports Audio")
            }
            else {
                alert("Your browser dosen't support Audio")
            }
        }

Demo view here

What if I want to use Modernizr and my own custom tests?

Modernizr has a rather nice feature that allows you to add custom tests to the library.

Modernizr.addTest("myAudioTest", function(){  
	 return !!document.createElement('audio').canPlayType;
});

You can then just call it like this (note that even though we added the test name in capitals Modernizr lowercases the property name) :

Modernizr.myaudiotest

So the demo above would look like this:

window.onload = function () {
            if (Modernizr.myaudiotest) {
                alert("Your browser supports Audio")
            }
            else {
                alert("Your browser dosen't support Audio")
            }
        }

Demo view here

Comments (2)

  1. Charmis says:

    If the browser is unable to create the audio element and the canPlayType property is true, this test will return true.

    I think a typo - instead of "unable" it should be "able"

  2. thebeebs says:

    Thanks @Charmis I have now corrected the article. Thanks for pointing the typo out.

Skip to main content