fmuser
fmuser

Reputation: 254

Modernizr Feature Detection with v3

I would like to ask if there's any significant difference/performance issue for detecting using the following two methods:

Let's say we're testing for 3d transforms.

Using the new function that Modernizr 3 offers:

Modernizr.on('csstransforms3d', function(result) {
  if (result) {
    element.className = 'myFirstClass';
  }
  else {
    element.className = 'mySecondClass';
  }
});

And with the standard way:

if (Modernizr.csstransforms3d) {
  element.className = 'myFirstClass';
} else {
  element.className = 'mySecondClass'
}

Upvotes: 1

Views: 475

Answers (2)

hexalys
hexalys

Reputation: 5257

The Modernizr.on function is only (or mainly) for asynchronous detects and deferred actions. See the full explanation and example by @stucox for more details.

csstransforms3d is not async, and available right away. There would be no reason to be using the on event callback method for it. The function is rather inefficient with setTimeout() calls which aren't good for performance.

Only use on for deferred events on async detects.

Upvotes: 1

Ansel Santosa
Ansel Santosa

Reputation: 8444

They aren't really comparable because depending on the situation, one will always be better suited than the other. Performance isn't really the issue.

The standard way, checking Boolean values in a Dictionary is an extremely fast operation. If you have a function that gets executed in reaction to some user interaction, this will be the best way to get feature info. For example:

$('#showVideo').on('click', function() {
    if (Modernizr.video) {
        // load HTML5 video
    }
    else {
        // load Flash video
    }
});

Similarly, listening to JS events is very efficient. What the new event-based model in Modernizr allows is for you to react to the Modernizr tests completing. This is great if your site needs to make changes ASAP when feature detection data is available. For example:

Modernizr.on('draganddrop', function(result) {
    if (!result) {
        alert('This site requires Drag and Drop. Please update your browser.')
    }
});

Previously you had to watch for DOM updates on the <body> and check the classes in order to get this information.

Upvotes: 1

Related Questions