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.

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: