Conditional CSS and JavaScript for Different Browsers

A common technique adopted by developers is to detect browsers and conditionally differentiate CSS rules and JavaScript for specific versions of browsers. In simple words, a requirement could be that if the browser is IE, use a different set of CSS and JavaScript files.

Let us see how to achieve this using conditional comments.

Conditional JavaScript

In the example shown above, if the browser is IE, iescript.js is included. For all other browsers, otherscript.js will be included. You can do the same for CSS files too.

Note: Devs use the technique of identifying browsers using vendor/version and other similar browser detection techniques. However these lead to what is termed as web maintenance nightmare and this technique is inappropriate. Instead of browser sniffing, what is recommended is ‘feature detection’. So if you have to execute code which relies on a browser feature, test it prior to the execution to ensure that the feature works properly.





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: