In defence of jQuery browser detection
Friday, May 22nd, 2009
I read somewhere the other week that jQuery is deprecating its jQuery.browser method, which means that in the future (though not yet, as the method still works but will not continue to be developed/supported, and will eventually be dropped) you will not be able to directly ask jQuery which browser it is being run in.
The rationale behind doing this is on the face of it sound: The reason you want to check what the browser is is that you want to check if a feature of javascript is available in that browser… so why not just ask if that feature is available, then the question of which browser it is becomes irrelevant. This will enable your script to continue to function (most probably) even in the unlikely event that eg Microsoft bring out a patch for ie6 that makes it fully support javascript.
But there is a flaw in this reasoning. It assumes that the only reason you would want to serve some different script to a browser is because of flaws in the browser’s javascript implementation, but in fact there are other reasons for doing this too, principally the browser’s failure to render CSS correctly.
While the new jQuery.support method does include tests for boxModel (ie6 and 7′s incorrect rendering of the CSS box model being the principle reason behind serving different CSS to different browsers) and one or two other CSS bugs, this simply isn’t up to the task. The box model is broken in ie6 and ie7, but broken in different ways, so normally to fix a layout bug I will want to serve different CSS to both.
Using various combinations of jQuery.support, eg
!jQuery.support.boxModel && jQuery.support.objectAll
you can still detect ie6 and ie7… but is this really an improvement on jQuery.browser?
jQuery.browser.msie && jQuery.browser.version.substr(0,1)=="6"
With jQuery.browser it is wholly transparent what you’re trying to detect, and if the code within the conditional’s braces contains a hefty amount of CSS rules your average developer should be able to work out the reason for the browser detection is to fix CSS bugs.
One other reason for explicitly detecting a browser (which I need at the moment as I’m developing a jQuery plugin) is that different browsers render form elements differently (the most obvious black sheep is safari’s making most elements look blue and glossy, but there are subtle differences in other browsers too). If I, say, want to fake a <select> element by using a <ul>, and want it to look convincing in all browsers I need to supply each browser with differentiated CSS. jQuery.browser would be the obvious way to do this. No matter how many CSS bugs get fixed in browsers, how to render form elements by default isn’t specified by CSS/html, so there will always be this reason to want to detect browsers.
jQuery.browser is a very useful feature and it’ll be a shame when it goes.






