Tuesday, May 31, 2011

How to Load Style Sheets based on the Browser type(ex: Internet Explorer, Firefox,....) in ASP.NET by using JavaScript


How to Load Style Sheets based on the Browser type(ex: Internet Explorer, Firefox,....) in ASP.NET by using JavaScript

The best approach is to use the JavaScript at the client side to make web browser request different style sheet file.  
 
<script language="JavaScript"> 
    
document.write('<link rel="stylesheet" href="http://www.yourdomain.com/'); 
    var 
agt=navigator.userAgent.toLowerCase(); 
    if (
agt.indexOf('opera') != -1document.write('opera.css'); 
    else if (
agt.indexOf('gecko') != -1document.write('mozilla.css'); 
    else if (
agt.indexOf('msie') != -1document.write('iexplorer.css'); 
    else 
document.write('default.css'); 
    
document.write('" type="text/css">'); 
    
</script>

If the JavaScript is disabled in the user's browser, we include the default style sheet file using the <noscript> tag.  

 <noscript> 
        <
link type="text/css" rel="stylesheet" href="default.css"> 
    </
noscript
>

Now, using that method all we need is to put that code in each web page, or you can put the JavaScript part in the separate file and include it using the html tag
<script type="text/javascript" src="yourscript.js" language="JavaScript"> 
</script>

Note that in that case you still need the <noscript>part to be in your web page.

Advantages: This method appears to be quite bulletproof. It works fine even if web cache server supplies same page to all the browsers because browser will request different stylesheet. One could say that this method makes the user's browser do the job for your the web server.

Disadvantages: The only problem we encountered is when user saves your web page locally and then opens it in another browser not naving an internet access. In this case browser won't be able to open needed stylesheet file and will render your web page using default settings.

You can see how this method works here jscssmethod.html (html source at jscssmethod.html.txt).




--
Regards:
M.Rama Subba Reddy
Cell:+919080391242

1 comment: