Not all browsers or browser versions support the same features at a given time. Therefore, you need to swap out or change functionality in your website based on the browser (version) the user has. A commonly used approach is to add browser detection code to your website which will provide the best experience based on the browser type and give a suboptimal experience to other browsers.
The concern with this approach is that you go away with browser evolution. Moreover, the browser type is often determined based on the user-agent string, which has been described as “an ever-growing pack of lies” by Patrick H. Lauke. All user agent strings actually contain more information about other browsers than the actual browser you’re using. Browsers specifically perform user agent spoofing to aid compatibility.
This blogpost is the fourth in a series about Modern Web development. We’ll be covering the following topics:
- CSS prefixes
- Browser and feature detection (this article)
- Rendering modes
Feature detection using the DOM
Let’s look at an example on how we can do feature detection using the DOM. In this example we have a canvas element on our website. Traditionally you use the user agent string to detect for a given browser, specifically the code sample checks for Internet Explorer version 9 and above.
Alternatively, instead of sniffing the user agent string, we can leverage the DOM to test for the availability of the canvas element in a given browser.
In below code sample you’ll notice that we first programmatically create a canvas element. In a second step, we execute the getContext() on the created element. The reason for doing this second step is because in some browser versions, if the element cannot be created, an empty element is still created.
So by creating an object programmatically, you can check that a given HTML element is available in a browser.
Feature detection using Modernizr
Modernizr has an elaborate list of feature detections available, both for HTML5 features as well as for performing CSS3 capabilities. You can find more information in the documentation center.
- Check out the Microsoft Edge Developer Center for valuable resources and tools when working with the Microsoft Edge browser.
- An in-depth overview on how to scan your site using the site scanner.
- View our complete video on Channel 9: Riding the Modern Web: Five things to consider as a web developer
- Download Visual Studio Code for free for a great cross-platform coding experience for web developers. Also check out our webinar on how to get started with Visual Studio Code.
For an overview of the 5 things to consider when developing for the modern web, check out our 17-minute video.