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.