Jan 08 2007

Adding each script only once

Lets face it - sometimes when we code we do mistakes. It would in our example of the JavaScript server control   be very easy to add the same script twice. It might not look that easy to do that mistake when just looking at the very simple example we have gotten so far - but in real life you might be adding the script statements from code instead of using the ASPX file, and even from within server controls.

A very simple "fix" for that problem:

The loop adding the script statement looks like this:




            //Additional plugin includes...
            foreach (IncludeFile oPlug in IncludeFiles)
            {
                string sInclude2 = this.ResolveUrl(oPlug.Path);
                MightAdd(sInclude2);
            }





and the function MightAdd:




        //Check for already existing?
        public void MightAdd(string sPath)
        {
            //Does it already exists?
            List<string> oList = null;
            if (Page.Items["JavaScriptServe.JSIncludeControl"] == null)
            {
                oList = new List<string>();
                Page.Items.Add("JavaScriptServe.JSIncludeControl", oList);
            }
            else
                oList = Page.Items["JavaScriptServe.JSIncludeControl"] as List<string>;


            //Does it exists?
            if (oList.Exists(sPath.ToLower().Equals) == false)
            {
                HtmlGenericControl Include2 = new HtmlGenericControl("script");
                Include2.Attributes.Add("type", "text/javascript");
                Include2.Attributes.Add("src", sPath);
                int nCount = this.Page.Header.Controls.Count;
                this.Page.Header.Controls.Add(Include2);
                oList.Add(sPath);
            }

        }


By "storing" a list of added script paths inside the page.items (instantiated per request) - (instead of just looping through the IncludeFiles collection ) we also get the positive side effect that we can now use multiple JSINcludeControl:s on the same page - and getting the correct unique checking across all controls.