Adding a Javascript File Dynamically in C# and ASP.Net


This concept is really basic but useful. Let's say that you have a rather large website with a couple different JavaScript files. Normally you would just attach the files to the pages as needed and go about your business. Let's say that one of the JavaScript files is a meg in size, it is only needed in specific situations, and the pages are dynamic in their content so you never know if the file is needed until the page is loading... At this juncture you can either add the file and pray that no one views your site (thus saving you bandwidth) or you can add the file dynamically only when those situations that it is needed occur (and pray that they do not come up that often). The second option is actually incredibly easy to accomplish using the following code:

   1: public static void AddScriptFile(string File,string Directory)
   2: {
   3:     System.Web.UI.Page CurrentPage = (System.Web.UI.Page)HttpContext.Current.CurrentHandler;
   4:     bool Added = false; 
   6:     foreach (Control CurrentControl in CurrentPage.Header.Controls)
   7:     {
   8:         if (CurrentControl.GetType() == typeof(HtmlGenericControl))
   9:         {
  10:             HtmlGenericControl HTMLGenericControl = (HtmlGenericControl)CurrentControl;
  11:             if (HTMLGenericControl.Attributes["src"] != null)
  12:             {
  13:                 if (HTMLGenericControl.Attributes["src"].Contains(File))
  14:                 {
  15:                     Added = true;
  16:                 }
  17:             }
  18:         }
  19:     } 
  21:     if (!Added)
  22:     {
  23:         HtmlGenericControl ScriptControl = new HtmlGenericControl("script");
  24:         ScriptControl.Attributes.Add("type", "text/javascript");
  25:         ScriptControl.Attributes.Add("src", Directory + File); 
  27:         CurrentPage.Header.Controls.Add(ScriptControl);
  28:     }
  29: }

The code above takes a look at the items within the header. If the header already has the file requested in their, it doesn't add it. Otherwise it adds that file. You can do this with javascript, CSS, etc. and it can save you quite a bit in bandwidth consumption some times (and depending on the site's setup, this code is damn near required). Or of course you can just use the built in functions: RegisterClientScriptInclude... You know, whichever is easier. Anyway, use the code (or preferably use the built in function), leave feedback, and happy coding.