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.

No comments:

Post a Comment