Wednesday, November 24, 2010

Loading CSS stylesheet for ascx ASP.Net user control

Goal:

For performance reasons you want to load a piece of CSS only for the ascx file to which it applies. You do not want to embed the style as you cannot do this in ASP.Net ascx user controls. ASP.Net will render the style tag as HTML text.

Solution:

Some folks use the Page.Header.Controls.Add to add the stylesheet link in the ascx page or in the code behind. Not needed, you may specify a "link" tag in the ascx file, not need to specify "head" tag or anything else, just the link tag itself:




<link rel="Stylesheet" media="screen" type="text/css" href="<%=ResolveUrl("~/Content/StyleSheets/Screen/Global/CssCRMUITrafficLine.css") %>" />


The benefits are significant in that it is only loaded when needed. Personally I also prefix all my css selectors with the unique ID of the ascx container (i.e. I give the outer most div of my ascx page a unique name - usually that of the ascx file name) so that when I nest the ascx file into any other file the nested dynamically loaded CSS to not affect anything else outside of its scope. Also, since the stylesheet is linked it is cached on the user's browser once it has been loaded.


No comments:

Post a Comment