Including JS file references in masterpages

 

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 "~"

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Master page</title>    
    <script language="javascript" src="~/App_Common/Scripts/tablecloth.js" runat="server"></script>
</head>
<body>

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.

 

References : http://forums.asp.net/t/908248.aspx

Published Friday, May 09, 2008 5:54 PM by sashidhar

Comments

# Including JS file references in masterpages - Sashidhar Kokku

Pingback from  Including JS file references in masterpages - Sashidhar Kokku

# re: Including JS file references in masterpages

Wednesday, October 08, 2008 10:26 AM by Kay

Many people have posted so called solutions to this issue around the web. Your solution is quick, clear and to the point. Many thanks!

# re: Including JS file references in masterpages

Tuesday, January 06, 2009 10:02 AM by Krunal.Shaholia

Good Article.Also would like to know how should we reference a java script in URL Rewriting.

# re: Including JS file references in masterpages

Wednesday, September 30, 2009 5:36 AM by Daniel

Excellent. Thanks!

# re: Including JS file references in masterpages

Wednesday, December 23, 2009 10:01 AM by canadian lipitor

It is important to remember that you must never double dose. If you miss a dose, don't go back to it, but continue following your schedule and take the next dose.

Leave a Comment

(required) 
(required) 
(optional)
(required)