问题
Yeah, I know that feature detection is preferable.
I've got a case in my codebase where we are using $.browser.msie
and $.browser.version
to decide whether to render some CSS or not. The developer who wrote the code is no longer with us, and I don't fully understand exactly what kind of feature detection I should write here instead.
As a quick fix, what's the shortest way to implement $.browser.msie and $.browser.version?
回答1:
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;
})();
回答2:
Use conditional comments instead of JavaScript.
<!--[if lte IE 7]>
<link rel="stylesheet" href="ie.css" type="text/css">
<![endif]-->
回答3:
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]-->
回答4:
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.
来源:https://stackoverflow.com/questions/14379539/whats-a-quick-pure-javascript-replacement-for-jquery-browser-removed-in-jquer