What's a quick, pure javascript replacement for jquery.browser (removed in jquery 1.9)?

家住魔仙堡 提交于 2019-12-05 09:42:30

I'll just copy the code from jQuery 1.8.3.

// Limit scope pollution from any deprecated API
(function() {

var matched, browser;

// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
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"
    };
};

matched = jQuery.uaMatch( 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;
})();

Use conditional comments instead of JavaScript.

<!--[if lte IE 7]>
<link rel="stylesheet" href="ie.css" type="text/css">
<![endif]-->

A quick fix so the script won't break until it's properly refactored (add conditional comments for other versions if needed):

<!--[if IE 7]>
<script> if(typeof $!== typeof undefined){ $.browser = { msie : true, version : 7 }} </script>
<![endif]-->
<!--[if IE 8]>
<script> if(typeof $!== typeof undefined){ $.browser = { msie : true, version : 8 }} </script>
<![endif]-->

JQuery released a Migrate plugin that restores $.browser when used with 1.9. Just be sure to use the production version of Migrate on production servers. The development version will generate a bunch of console messages telling you where your code would break in 1.9 sans Migrate.

Using JQuery Migrate to restore $.browser probably isn't the best long term solution, however. As the name implies, it's intended as a transitional tool, and I don't know that its browser detection functionality will be actively maintained. An alternative would be Modernizr.

What I personally will be doing is keeping my production site on JQ 1.8 for the time being, and testing things out with the development version of Migrate on my dev machine to get a better idea of what 1.9 will break (they did a lot more than just remove $.browser) before deciding on an upgrade strategy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!