A real JavaScript and CSS include method

After being displeased with the lack of a real JavaScript include method, and the complete absence of a CSS include method in ASP.NET, I started putting this into all of my BasePage classes. It uses Page Context to protect itself from double entries.

        protected void RegisterJavaScriptInclude(string path)
        {
            if (!Context.Items.Contains(path))
            {
                HtmlGenericControl js;
                js = new HtmlGenericControl();
                js.TagName = "script";
                js.Attributes.Add("type", "text/javascript");
                js.Attributes.Add("src", path);
                Page.Header.Controls.Add(js);
                Context.Items.Add(path, "JSINCLUDE");
            }
        }

        protected void RegisterCssInclude(string path)
        {
            if (!Context.Items.Contains(path))
            {
                HtmlGenericControl css;
                css = new HtmlGenericControl();
                css.TagName = "link";
                css.Attributes.Add("rel", "stylesheet");
                css.Attributes.Add("type", "text/css");
                css.Attributes.Add("href", path);
                Page.Header.Controls.Add(css);
                Context.Items.Add(path, "CSSINCLUDE");
            }
        }

About Jeremy Mullinax-Hill

I am a lead/senior developer with more than 10 years experience in both the public and internal applications for Fortune 500s and mid-sized View all posts by Jeremy Mullinax-Hill

Leave a comment