Decrease Font Size
Increase Font Size
   BLOG

ASP.NET load Stylesheet dynamically with no duplicate

ASP.NET load Stylesheet dynamically |

How to load CSS for page dynamically |

Dynamically loading a CSS file |

Dynamically add link to CSS Stylesheet? |

ASP.NET load Stylesheet dynamically with no duplicate

 

I have an ASP.NET WebUserControl that requires a CSS Stylesheet to display correctly. My goal is to not include the CSS stylesheet in any of my Page or Masterpage whenever I consume the WebUserControl. All I want to do is just drag and drop one or more of the WebUserControl on to my page and I'm good to go. I can solve this maze by loading the CSS stylesheet in my user WebUserControl dynamically. But it will load duplicates CSS on my page if I have more than one of the identical WebUserControl. If you happen to come across into this kind of situation, here is the solution on how to prevent loading duplicate CSS stylesheet on your page. It works for me, comments are welcome.

Use this code in the WebUserControl

protected void Page_Load(object sender, EventArgs e)
    {
		LoadCss();
}

//load style css
    internal void LoadCss()
    {
        //prevent loading multiple css style sheet
        HtmlControl css = null;
        if (Session["MultipleSelectionDDLCSSID"] != null)
        {
            css = Page.Header.FindControl(Session["MultipleSelectionDDLCSSID"] as string) as HtmlControl;
        }
       
        if (css == null)
        {
            //load the style sheet
            HtmlLink cssLink = new HtmlLink();
            cssLink.ID = "MultipleSelectionDDLCSSID";
            cssLink.Href = "StyleSheet.css";
            cssLink.Attributes.Add("rel", "stylesheet");
            cssLink.Attributes.Add("type", "text/css");

            // Add the HtmlLink to the Head section of the page.
            Page.Header.Controls.Add(cssLink);

            Session["MultipleSelectionDDLCSSID"] = cssLink.ID;
        }
    }