JavaScript Feature Detection with has.js

By on  

Dojo Toolkit Project Lead Peter Higgins has been working on an exciting new project called has.js.  Higgins describes this project best:

Browser sniffing and feature inference are flawed techniques for detecting browser support in client side JavaScript. The goal of has.js is to provide a collection of self-contained tests and unified framework around using pure feature detection for whatever library consumes it.

Simply put, has.js tests the browser environment to discover if the browser supports any given feature.  has.js includes a growing number of tests, ranging in many categories, including:

  • EcmaScript 5 features (Object.freeze, Array.map, etc.)
  • CSS features (rgba, border radius, etc.)
  • HTML5 and advanced JavaScript APIs (classList, placeholder attribute, etc.)
  • Script loading features (defer, async)
  • Native JSON, Audio, Video support
  • XHR support
  • ...and more!

Let's explore how to use has.js, its modular test collections, and create custom feature detection tests.

has.js Usage

has.js uses a global has function which you pass a string to test against.  If we wanted to test the presence of a natively supported Array.forEach method, we would code:

// If Array.forEach is not present...
if(!has("array-foreach")) {
	// ... create it!
	Array.prototype.forEach = function() {
		// ....

The string passed to the has function represents the test's key as defined when the test was created.  What's a real test creation look like?  Let's review one!

has.js Test Creation

The code behind the Array.forEach test is short and sweet:

(function(has, addtest, cssprop){

	var toString = {}.toString,
		FUNCTION_CLASS = "[object Function]";

	addtest("array-foreach", function(global, document, anElement){
		return toString.call(EMPTY_ARRAY.forEach) == FUNCTION_CLASS;
})(has, has.add, has.cssprop);

has.js also provides an ES5 Array check which includes other has tests:

(function(has, addtest, cssprop){
	addtest("array-es5", function(){
		return has("array-every") && has("array-filter") && has("array-foreach") &&
		has("array-indexof") && has("array-isarray") && has("array-lastindexof") &&
		has("array-map") && has("array-reduce") && has("array-reduceright") &&
})(has, has.add, has.cssprop);

Simple enough to create tests, right?  Let's create a few of our own!

Custom has.js Test Creation

As you hopefully noticed in the tests above, the test itself is actually a function that returns true if the browser supports a given feature or false if the browser does not.  Let's create a test that tells us if the browser supports RGBA.

addtest("css-rgba", function(g, d, el){
    var re = /^rgba/,
        supported = null;

          el.style.color = "rgba(1,1,1,0.5)";
          supported = re.test(el.style.color);
          el.style.color = "";
    return supported;

A test may also return null if a test is not applicable to the current browser. For example, browsers other than IE will return null for ActiveX, as ActiveX is an Microsoft-only technology.

Creating has.js modules specific to your project may be the best option if your web application requires many different features. These abstractions may allow you to code your application faster.

has.js is Growing!

has.js is still in its infancy but the utility clearly has a bright future.  The beauty of has.js is that its functionality is extremely useful but the tests themselves are very simple to create.  If you have ideas for more tests or simply improvements to has.js, feel free to fork the project and send pull requests to the main repo.

Track.js Error Reporting

Recent Features

  • I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

Incredible Demos


  1. Stupid question:
    Why does everyone compare the toString() value of an object to test whether it is a function? I’m referring to the code behind the Array.forEach test.

    Why not obj.constructor === Function?

  2. Duncan Krebbers

    How is this compared with modernizr? It seems a bit equal to me.

    • I want to say that modernizr is more targeted toward CSS. I see modernizr is adding CSS class and such. has.js simply provides a true or falsey value.

    • The ultimate goal with has.js is to embed it in other libraries by way of a customized “builder”, including only tests you want. The hope is that Modernizr would simply be a specific export of various tests, with Modernizr adding in the functionality to do things like add class names to the element etc.

      Paul irish, of Modernizr, is also on the has.js team. The tests are mostly identical between the two. Only the API surface differs.

    • Paul Irish, a maintainer of Modernizr, is also a contributor to has.js. Besides adding the className’s to the documentElement, Modernizr also executes all tests at once, where has.js allows for deferred testing (test when u need it). Modernizr also applies the “HTML5 shim” to allow HTML5 elements to be styleable in older IE.

      There are also differences in what each project considers supported. For example Modernizr will report that input type=range is supported in browsers like Safari 3 despite lacking much of the required HTML5 API.

  3. I’ve been playing around with the Modernizr script which does all testing at once, as mentioned above. I assume you could do the same with has.js? Is there a demo page with running code some where. I’m not sure of what is the intended ‘best way’ to call individual or all test of browser capabilities thru has.js. Is it Dojo like, in that you call individual test modules as needed?

  4. Follow-up: I download the has.js bundle and found the test page at ‘/tests/runTests.html’. Very nice collection of tests. Wish I had this sooner. I would prefer a Dojo style of loading files with something like has.require(‘video’) and so forth. And I’m still a little confused, as I’m still not sure what variable to access for what category of test(s): ie some sort of Dojo style naming convention like ‘has.video.test-name’ might be nice. But the project is still new and from your description, they want to remain ‘generic’, so I will dig around some more for insight.
    Thanks for the post.

  5. AprilMorone (aka 'linuxwebdeveloper')

    When I’d had the HTML and Dynamic HTML class as a part of my AAS degree as a Computer Support Specialist around the same time as I was doing Web Dev stuff, I’d been required as part of one of my class projects to use modernizr. I agree with David Walsh as to it’s effects and to what it affects because I got to see, first hand, what it (modernizr) does. I think using has.js could be a better choice.

  6. I’m referring to the code behind the Array.ie some sort of Dojo style naming convention like has.video.test-name might be nice

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Loading Static Templates for Intern Testing

    I use Intern by SitePen for all of my JavaScript functional testing.  Intern has loads of features other functional test frameworks don't and it's completely Promise-based -- something I got very used to when I used the Dojo Toolkit every day. Async test creation can...

  • Convert Video to mp3

    Let's all be honest for a moment:  we've all ... not paid for ... music.  Whether it was via a file sharing app like Kazaa or Napster, or it was downloading and seeding on bittorrent, or maybe even downloading a music video and ripping its audio,...

  • Sort git Branches by Date

    I'll be first person to admit I don't do as much git repository maintenance as I should.  I rarely delete branches which have been merged, so a git branch execution shows me a mile-long list of branches that likely aren't relevant.  The best way to find branches I've recently...

  • Best Tools and Resources for Web Professionals in 2015

    Looking for the right resources to help you satisfy the needs of your clients? On the lookout for the best tools to help you increase your revenue? Searching for the right software to help you improve your business? Well, then you’ve come to the right place....

  • JavaScript Polling

    Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices.  Sometimes there isn't the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for...