HTML5 feature detection aka Modernizr
Tuesday 08 November 2011
Yesterday I blogged about using the new Server-Sent Events or the EventSource object to send messages from the server to the client. But what happens if I try to do this in a browser that doesn’t support Server-Sent Events?
If I run the code from yesterday in Internet Explorer 9 I sill see the following error dialog:
The reason is that IE 9 doesn’t support Server-Sent Events, see CanIUse.com, so it results in an Microsoft JScript runtime error: 'EventSource' is undefined exception
HTML5 Feature detection
In the old days if web development we used to check the browser the client was using and make decisions based on the bowser type and version. These days that is no linger a recommended approach as browsers are updated frequently and keeping up to date base on browser versions would be a nightmare.
A better approach, and much more common these days.. is feature detection. Feature detection basically checks if a specific feature is available in a given browser. And because that uses tests based on the official API it is much easier to maintain and more reliable as it doesn’t depend on specific browsers.
In the case of the Server-Sent Events we can check for the existence of the EventSource object using the following test:
This would work just fine but it means we have to create checks and make sure these work in every browser.
Modernizr to the rescue
The developers solution
Developer write code for their day to day business so as a developer when I have a problem I am going to write some code to solve this problem. By adding Modernizr to the mix and adding a simple check we can use the following code and get the result below.
Not bad but we can do even better
Suppose I use the following HTML:
We get the following result:
When doing HTML 5 work you just have to live Modernizr