jQuery $.browser detection as a Separate File

As jQuery has removed $.browser from the versions > 1.9.0, I found myself extracting it to be used in my own projects that depended on the feature.

jQuery does provide jQuery Migrate plugin which includes the following code, but it also includes a lot of other things you might not need. I saw a couple of requests on the official blog and thought I’d put this live in case it helps anyone else.

Note: I highly recommend using tools like Modernizr for feature detection. Only use $.browser if you really need to detect the browser vendor!

Gist: https://gist.github.com/adeelejaz/4714079

(function( jQuery, window, undefined ) {
"use strict";
var matched, browser;
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
// Don't clobber any existing jQuery.browser in case it's different
if ( !jQuery.browser ) {
matched = jQuery.uaMatch( window.navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
}
})( jQuery, window );

Flattr this!