Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67131

Why is $.browser deprecated - and what is a better alternative?

So I know $.browser has been deprecated and "frowned upon", since jQuery 1.3, but it continues to exist & work in the code.

It's still using the plain javascript: navigator.userAgent to determine the browser being used, as well as the version.


Now is there something about these I don't know about navigator itself, that I shouldn't be using either $.browser or plain vanilla JS to get the browser/version? I just want to make sure when they have IE8 (for example), they really do have it, and I'm not processing the wrong code.


What other alternatives do we have for browser sniffing? I know about $.support, I use modernizr, but sometimes I need just need the down and dirty browser version, instead of seeing what the browser is capable of handling (I think that is a completely different problem solver).

Upvotes: 0

Views: 839

Answers (3)

Kerem
Kerem

Reputation: 11586

If a "must" to know which browser on the page for me, I use this personally;

(function() {
    var re_browsers = {
        firefox: /firefox\/([\d\.]+)/,
        chrome: /chrome\/([\d\.]+)/,
        safari: /webkit.*?version\/([\d\.]+)/,
        opera: /opera.*?version\/([\d\.]+)/,
        ie: /msie\s+([\d\.]+)/
        // ...
    };

    var ua = window.navigator.userAgent.toLowerCase(), k, re, browser = {};
    for (k in re_browsers) {
        if (re = re_browsers[k].exec(ua)) {
            break;
        }
    }
    browser[k] = true;
    browser["version"] = parseFloat(re && re[1]);
    browser["versionOrig"] = re[1];

    jQuery.extend({browser: browser});
})();

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382274

Generally it's recommended not to try to guess what the browser is but to check if a function is available. There are too many browsers and variants.

To check if a function is available, you simply do this :

if (!Array.prototype.map) {
    // not available, shut down computer !

Upvotes: 1

James Gaunt
James Gaunt

Reputation: 14783

You kind of answer the question yourself. The ideal is to check for feature support. As more browsers and devices come onto the market this approach should scale.

However if you want to do something 'down and dirty' then browser detection of course works, but only so far as you will know your code works in the existing set of browsers (or even just those you've tested your code with).

Upvotes: 1

Related Questions