Javascript in Master Pages
Creating a basic Master Page in ASP.NET 3.5 is pretty simple and straightforward, but it can be a little tricky getting all of your links and file paths to work properly on every page.
Figuring out the proper web controls for making URLs, images, and stylesheets to work was straight forward. However, getting the Javascript external files working, other than on the landing page, was more difficult. For some reason, Microsoft doesn’t allow the <head runat=”server”></head> tag change the Javascript path automatically like the external stylesheets.
Below is a cheat sheet for linking stylesheets, Javascript, links, and images to a Master Page.
Stylesheets
Make sure you place your external stylesheet path(s) between the following tags:
<head runat=”server”>
<link rel="stylesheet" href="css/example.css" type="text/css"
media="screen" />
</head>
The URL path will change automatically depending which page you are on.
Javascript
Similarly to the external stylesheet path(s), you should place your Javascript path(s) between the following with the added code:
<head runat=”server”>
<script type="text/javascript" src='<%= ResolveClientUrl
("~/js/example.js") %>'></script>
</head>
ResolveClientUrl – this returns a URL relative to the folder containing the source file.
Links
<asp:HyperLink ID=”example” runat=”server” Text=”Example” NavigateUrl=”~/directory/example.aspx” ToolTip=”Example”></asp:HyperLink>
- Text = <a href=””>Text</a>
- NavigateURL = href
- ToolTip = title
Images
<asp:Image ID=”example” runat=”server” ImageUrl=”~/images/example.gif” AlternateText=”Example Image /”>
- ImgUrl = src
- AlternateText = alt
If you know of any other solutions on how to make Javascript work in a Master Page other than using ResolveClientUrl, I would be interested to know.
Enjoy!
User Comments
Aaron,
I found your site via a link in the recent ASP.NET tutorial on Nettuts. I like your blog, and particularly found this post useful, because I ran into this same issue just last week.
I ended up using this code:
<script type="text/javascript" src="/js/jquery/jquery-1.3.2.min.js”>
I don’t know which is better, but I’m glad I found your post, and I appreciate you sharing the tip.
@ Ben
Thanks for the comments and I’m glad you found this useful. At the time I wrote this I was just digging into ASP.NET. I also found that you can also add Javascript in the masterpage inside the scriptmanager tags.

Ben Harrison says: