Monday, January 23, 2006
by Nik Kalyani
Monday, January 23, 2006 10:48:53 AM (Pacific Standard Time, UTC-08:00)

There are many situations when you may want to dynamically add a stylesheet to a page. One use case is when a control is being dynamically loaded and it comes with its own stylesheet. If you don’t know that the style is needed in advance or are dealing with an environment where you have a stylesheet for a control but don’t have control of the page (as it is in DotNetNuke), there are two common methods in use:

1) Add a <LINK> tag: This works but leaves the parent page non-XHTML compliant since <LINK> is only valid in the <HEAD> section.

2) Add a <STYLE> element and add the styles to the page. This works but gives you a bloated page and does not take advantage of stylesheet caching.

The solution is to dynamically add a stylesheet to the page. Here’s how.

(Internet Explorer makes this easy to do with Javascript using document.createStyleSheet. For other browsers, you have to get a handle to the <HEAD> element and then insert the stylesheet.)

bool isIE = (HttpContext.Current.Request.Browser.Browser == "IE" ? true : false);
string stylesheetUrl = “/test/default.css”;
StringBuilder styleScript = new StringBuilder();
styleScript.Append("<script language=\"javascript\">");
if (isIE)
    styleScript.Append("document.createStyleSheet(\"" + styleSheetUrl + “\");");
else
   
styleScript.Append("var newStyleSheet=document.createElement(\"link\"); newStyleSheet.rel=\"stylesheet\";   newStyleSheet.href=\"" + styleSheetUrl + “\”; document.getElementsByTagName(\"head\")[0].appendChild(newStyleSheet);");
styleScript.Append("</script>");
Page.RegisterClientScriptBlock(“MyStylesheet”, styleScript.ToString());

For IE, the script adds the stylesheet directly. For other browsers, it creates a new <LINK> element on the page and then adds it at the end of list of <HEAD> elements.

 

RSS feed
Search and Links
Bling

View Nik Kalyani's profile on LinkedIn

Contact me: nik*kalyani.com (replace "*")

TechBubble
www.flickr.com
This is a Flickr badge showing public photos from techbubble. Make your own badge here.
Statistics
Total Posts: 204
This Year: 22
This Month: 0
This Week: 0
Comments: 231
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008
Nik Kalyani
Sign In
All Content © 2008, Nik Kalyani