Reputation: 4052
In the past time, if I'm not sure with something is supported or not,
I'll type If(something){ ... } in Javascript.
Recently I find Modernizr is also easy to detect browser's support.
It will add class to HTML and create an object called Modernizr,
But I'm confusing why we don't use If(something) but if(Modernizr.something)
For example:
what is difference between if(window.history){...} and if(Modernizr.history) {...}?
Upvotes: 0
Views: 194
Reputation: 5152
Because it's not always that simple. If you only need to check for window.history
you don't need modernizr. But if you have to check for other futures, you should use modernizr because it has implemented the best and lightweight methods to detect this futures. Take a look at the source code, for example the hashchange
detection:
isEventSupported = (function() {
var TAGNAMES = {
'select': 'input', 'change': 'input',
'submit': 'form', 'reset': 'form',
'error': 'img', 'load': 'img', 'abort': 'img'
};
function isEventSupported( eventName, element ) {
element = element || document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
var isSupported = eventName in element;
if ( !isSupported ) {
if ( !element.setAttribute ) {
element = document.createElement('div');
}
if ( element.setAttribute && element.removeAttribute ) {
element.setAttribute(eventName, '');
isSupported = is(element[eventName], 'function');
if ( !is(element[eventName], 'undefined') ) {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
}
element = null;
return isSupported;
}
return isEventSupported;
})(),
Why would you implement this by your own when modernizr does it for you in a proved and fast way?
Upvotes: 3