Including script files in masterpages (ASP.NET)

One of the issues I have faced with including site-wide JS files while developing web-applications is the simple fact that I was developing in Windows XP and IIS 5. And IIS puts in each of my websites as virtual-directories. So , I always have trouble including references to js files from the master-pages.

One alternative was to have a virtual directory outside the project structure and point it to the js folder, and my references would work properly. But there are other nicer ways to do the same.

1. Include the script tag as a server side tag, and give the reference to the file with a “~”

 <script language="javascript" src="~/App_Common/Scripts/tablecloth.js" runat="server"></script>

2. Add some code to your masterpage’s load event that would register the file after resolving the client url.

 protected void Page_Load(object sender, EventArgs e) { this.Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "tableCloth", this.ResolveClientUrl("~/App_Common/Scripts/tablecloth.js")); } 

The above two approaches completely avoid having to create a virtual directory of any kind, and work all the time … so long as the path is correct.

Leave a Reply