Really Simple Browser Detection with jQuery

Post #729 categorized as Function, Presentation, last updated on Dec 14, 2009
Tagged with browsers, camino, css, firefox, ie, javascript, jquery, opera, safari

For my Serious redesign, I push the envelope in terms of CSS’ advanced selector functionality. Stuff like:

  • p:first-child
  • p:first-child:first-letter
  • p:first-child:after
  • p:first-child:first-line

Plus lots of other stylistic tricks that require CSS3 support in order to display as intended. Fortunately, most of the browsers to which I am catering with this new design have no problems with most of the advanced stuff. Of course, Internet Explorer chokes on just about everything, but fortunately IE’s proprietary conditional comments make it easy to fix things up with some “special” styles:

<!--[if IE 6]>
	<link rel="stylesheet" type="text/css" media="Screen" href="http://perishablepress.com/press/wp-content/themes/serious/css/ie6.css" />
<![endif]-->
<!--[if IE 7]>
	<link rel="stylesheet" type="text/css" media="Screen" href="http://perishablepress.com/press/wp-content/themes/serious/css/ie7.css" />
<![endif]-->
<!--[if IE 8]>
	<link rel="stylesheet" type="text/css" media="Screen" href="http://perishablepress.com/press/wp-content/themes/serious/css/ie8.css" />
<![endif]-->

Bam, just like that. In each of these stylesheets, I essentially “undo” all of the cool CSS effects that modern browsers get, including some crafty <pre> treatments that you are hopefully enjoying ;) Notice that we can specify an additional/alternate stylesheet for any version of IE. For the Serious theme, I provide around 20 remedial rules for IE 6, 7, and 8. Once IE 9 is released, we’ll need four additional stylesheets. Moving on..

So that takes care of Microsoft, but there are still other browsers to consider. I designed the new Serious theme to look perfect in the latest version of Firefox (3.5), which uses a different rendering engine than Safari, Opera, and Chrome. Fortunately, I didn’t need to change much for older versions of Firefox, but some of the other modern browsers required a few tweaks to get things looking just right. To do this, I could have used a bunch of ugly CSS hacks, but there are too many risks and “gotchas” when it comes to differentiating between Safari and Opera, for example. So I decided to keep things as simple and specific as possible. Here’s how I did it..

Really Simple Browser Detection for Modern Browsers

Before getting into it, let me just acknowledge that browser detection should only be used as a last resort. If you can design a site without needing any hacks or alternate presentational trickery, then good for you, no browser detection needed. When it comes to pushing the envelope and trying new things, however, you’ll almost always find presentational discrepancies in modern browsers. In any case, it turns out that I do feel as if browser detection was the ideal solution for the new design, mostly due to the fact that the modifications were few and fairly cosmetic in nature, so no big deal if JavaScript is not available to the user.

Basically, I want to apply an additional stylesheet to each of the modern browsers. To do this with IE, conditional comments work perfectly. I almost wish that every browser included some sort of conditional-comment functionality. It would make all this browser-detection stuff unnecessary. In any case, here is a list of browsers that I want to target with CSS (in no particular order):

  • Camino
  • Chrome
  • Opera
  • Safari

For these four browsers, I created four unique stylesheets and then conditionally link to them with a few snippets of jQuery:

<div class="altcss">

	<script type="text/javascript">$.browser.camino = /camino/.test(navigator.userAgent.toLowerCase()); if ($.browser.camino) { 
	document.write('<link rel="stylesheet" href="http://domain.tld/css/camino.css" type="text/css" media="screen">'); }</script>

	<script type="text/javascript">$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); if ($.browser.chrome) { 
	document.write('<link rel="stylesheet" href="http://domain.tld/css/chrome.css" type="text/css" media="screen">'); }</script>

	<script type="text/javascript">$.browser.opera  = /opera/.test(navigator.userAgent.toLowerCase());  if ($.browser.opera)  { 
	document.write('<link rel="stylesheet" href="http://domain.tld/css/opera.css"  type="text/css" media="screen">'); }</script>

	<script type="text/javascript">$.browser.safari = /safari/.test(navigator.userAgent.toLowerCase()); if ($.browser.safari) { 
	document.write('<link rel="stylesheet" href="http://domain.tld/css/safari.css" type="text/css" media="screen">'); }</script>

</div>

Basically, each of these snippets tests the client’s user-agent string and writes a <link> to any matching stylesheet. Of course JavaScript is required on the user’s browser, so it’s best not to use this technique for anything beyond minor cosmetic enhancements.

As for the code itself, I am know there are more elaborate ways of sniffing and detecting browsers, but I wanted to keep things as simple as possible. Also, this code could also be simplified to exist within a single <script> element:

<div class="altcss">

	<script type="text/javascript">

		$.browser.camino = /camino/.test(navigator.userAgent.toLowerCase()); if ($.browser.camino) { 
		document.write('<link rel="stylesheet" href="http://domain.tld/css/camino.css" type="text/css" media="screen">'); }

		$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); if ($.browser.chrome) { 
		document.write('<link rel="stylesheet" href="http://domain.tld/css/chrome.css" type="text/css" media="screen">'); }

		$.browser.opera  = /opera/.test(navigator.userAgent.toLowerCase());  if ($.browser.opera)  { 
		document.write('<link rel="stylesheet" href="http://domain.tld/css/opera.css"  type="text/css" media="screen">'); }

		$.browser.safari = /safari/.test(navigator.userAgent.toLowerCase()); if ($.browser.safari) { 
		document.write('<link rel="stylesheet" href="http://domain.tld/css/safari.css" type="text/css" media="screen">'); }

	</script>

</div>

And of course, you aren’t limited to the browsers specified here. You could easily target another by emulating the pattern according to the user-agent or name of the additional browser. For example, we could add a custom stylesheet for the Flock browser like so:

<script type="text/javascript">$.browser.flock = /flock/.test(navigator.userAgent.toLowerCase()); if ($.browser.flock) { 
document.write('<link rel="stylesheet" href="http://domain.tld/css/flock.css" type="text/css" media="screen">'); }</script>

Finally, because this is JavaScript, I place this block of code at the end of my XHTML document, just before the closing <body> element. It could just as easily be argued that this code should be placed in the document <head> because it’s ultimately referring to CSS, but I will leave it up to you to decide for yourself.

Update: in the comments, Gustavo informs us that, as of jQuery 1.4, the $.browser variable is replaced by $.support. So if you’re using jQuery 1.4 or better, you’ll need adjust the code accordingly. Here is an example showing how this would look for the Flock browser:

<script type="text/javascript">$.support.flock = /flock/.test(navigator.userAgent.toLowerCase()); if ($.support.flock) { 
document.write('<link rel="stylesheet" href="http://domain.tld/css/flock.css" type="text/css" media="screen">'); }</script>

Subscribe to Perishable Press


30 Responses

TopLeave a comment

[ Gravatar Icon ]

#1Tyler Abell

Sounds great, I am always worried that a user will not have JavaScript enabled, thats why I tend not to depend on JavaScript. Yes, it will look best with JavaScript but I always make sure it looks great without it. I as well tend to stay away from CSS3 depended elements, and other elements such as “border-radius”.

[ Gravatar Icon ]

#2Jeff Starr

Hey Tyler, absolutely - using a bit of JavaScript for the purposes of progressively enhancing your site with some advanced selectors or other CSS3 tricks is a great way to go about it. The way I see it, people who want the best experience on the Web will be using an updated version of one of the better browsers, Firefox, Opera, Safari, et al. It is unlikely that people visiting with old IE or other antiquated browsers will even notice the difference.

[ Gravatar Icon ]

#3Tyler Abell

That is completely true, especially those visiting your website, one that is of design would hopefully be updated and using a modern browser. I see your point…

[ Gravatar Icon ]

#4ufucuk

Extending codes in your article sucks. I can’t see the whole code since it extends onmousemove action.

[ Gravatar Icon ]

#5Gustavo

Have you looked at the latest jQuery 1.4 changes? $.browser is being replaced by .support -
It would be great if you had a 1.4 update to this article.

[ Gravatar Icon ]

#6Jeff Starr

@ufucuk: yes, I am aware of the issue and looking for a good solution. In the meantime, all you need to do is copy/paste the code into a text editor to take a look at it. Or read it in your feed reader.

@Gustavo: Thanks for the heads up - I will update the article soon with a note about the replacement. Good call.

[ Gravatar Icon ]

#7Matt Farmer

Great looking site, but I’ve always been against requiring a second technology to fix the first when you CAN do it in the first.

That being said, I think I like the method over at http://www.tvidesign.co.uk/blog/CSS-Browser-detection-using-jQuery-instead-of-hacks.aspx . With this your able to keep all of your CSS styles for each browser right next to each other, can keep all of your JS at the bottom of a document with out delaying rendering, and limit the number of network connections.

Do you see any flaws in this logic?

[ Gravatar Icon ]

#8Jeff Starr

Hi Matt,

Thanks for the comment. I completely agree about solving problems as simply as possible, but there are many cases where CSS is simply insufficient to meet the goals of a design (e.g., as discussed in the article). Not even with CSS hacks could I have created this theme (I tried!) - hence the JavaScript solution.

As for the logic behind your recommended method, I think it sounds great. Of course either technique includes the JavaScript at the bottom of the document, and either is going to result in the same number of network connections. So not really much difference other than having everything prepackaged and ready to go.

I guess it all comes down to personal preference. For this design, I really like having the granular control over each stylesheet. It’s just so clean and precise. With that external script you mention, I think it just would’ve been overkill.

Even so, it looks like a great tool to have in the belt and I look forward to trying it out on future projects. Thanks for pointing it out.

[ Gravatar Icon ]

#9Helen

By the way, the expanding-on-hover code area is a wonderful idea, Jeff.

[ Gravatar Icon ]

#10Trav

Concur with Helen, the mouse-overs are way cool. I’ve been looking at them for a few weeks now, and I only just noticed that effect today- did you just enable it or have I been totally blind? Nicely done!

[ Gravatar Icon ]

#11Art2code

thx a lot for the tricks !

[ Gravatar Icon ]

#12rodman

wow this is such a useful tutorial, thanks for sharing on your blog! I know good tutorials aren’t easy to come by these days, but following this was so easy and it’ll be useful on my website

[ Gravatar Icon ]

#13Don

Hi Jeff,

what I dont understand is: Why you wrap the jquery-code in that “altcss” class?

[ Gravatar Icon ]

#14Jeff Starr

Hi Don, good question! I use that in my designs to hide the contents and prevent them from breaking the layout. You can read more about it here.

[ Gravatar Icon ]

#15Tongkat

Very useful, love this! : )

[ Gravatar Icon ]

#16tb

Hi Jeff,

in jQuery 1.4 $browser is still supported but deprecated. The $support does not replace the $browser as you suggested above, rather it checks for the standards a browser supports.

I assume the reasoning behind that is to elaborate on object detection:
http://www.quirksmode.org/js/support.html

$browser is still good in 1.4 but not recommended
http://api.jquery.com/jQuery.browser/

$support does not check for particular browsers but rather for what a certain browser supports - be it html5 CSS3 etc.
http://api.jquery.com/jQuery.support/

Thanks still for the nice insights …

[ Gravatar Icon ]

#17Jeff Starr

Hi tb,

Thanks for the information. Is there a better way to go about it using jQuery?

[ Gravatar Icon ]

#18tb

Hey Jeff, I have not quite understood the support tag itself, but it seems that one can actually add to it as you are actually doing it … currently i am trying to figure out how to provide fallback for html5 funtionality as such. Your code is actually correct I think, I just could not find the var flock at the jQuery $support page my mistake … Still I might write a plugin checking only for html5 tags as such … thanks again for the pointers in the right direction

cheers

[ Gravatar Icon ]

#19HansBKK

RE: $browser is still good in 1.4 but not recommended

Actually, the whole “feature detection” over “browser detection” thing is 100% true when it comes to coding in javascript.

Here’s a bit more “toned down” version of the same information:

http://docs.jquery.com/Release:jQuery_1.3#No_More_Browser_Sniffing

When (as here) using javascript to serve different stylesheets (or IMO better idea to put browser-identifying classes on body or html), then browser detection is fine *if properly used*.

Which means (as here) for progressive enhancement, non-essentials like design-y show-off stuff, not relying on javascript for basic content/navigation functionality.

Of course, people who aren’t 100% sure they know what they’re doing, or looking to just get bulletproof sites coded to deadlines should just use bog-standard HTML/CSS and not worry about all the bleeding-edge stuff. Cause doing fancy stuff like this will blow out a project’s time budget geometrically, and few clients will pay for the pixel-perfection tweaking time. Staying up all night on your own site, well if that’s your idea of fun go for it! 8-)

Share your thoughts..

TopRead official comment policy

The rules are simple. Comment intelligently. Stay on-topic. Don’t spam! Suspected spam will be deleted. Use your real name or nickname, not a site name or business name. Using a site name or business name is a good way to get your link or comment removed. Certain comments are moderated; if your comment does not appear after several days, or if you wish to comment privately, contact me. Also, by posting a comment, you grant this site a perpetual license to reproduce your comment, name, and website URL. Lastly, you may use basic HTML markup, but please do not use <pre> tags. Instead, wrap your code with <code> tags. Use a new set of <code> tags for each code term or phrase, as well as for each individual line of code (i.e., multiple lines of code require multiple code tags). Please see the complete comment policy for more information.