Rebasing Javascript via a MasterPage

I’ve been looking for a way to rebase the URL for the javascript we include in our master pages. We add a lot of javascript in the master pages such as the following.

    <link href="../css/ui-theme.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript" src="../js/jquery-1.3.js" />

The problem is, as everyone probably knows, the relative path to the file is from the master page, not from the client page. For some reason, ASP.Net is kind enough to rebase the link tag’s href property, but not the javascript link.

After asking the Google, I saw a lot of examples to solve the problem like by using the ResolveClientUrl as follows:

    <script language="javascript" type="text/javascript"
        src='<%= ResolveClientUrl("~/js/jquery-1.3.js") %>' />
    <!-- or -->
    <script language="javascript" type="text/javascript"
        src='<%# ResolveClientUrl("~/js/jquery-1.3.js") %>' />

However, I saw no one suggest this, which I believe to be a little cleaner.

    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        <Scripts>
            <asp:ScriptReference Path="~/js/jquery-1.3.js" />
        </Scripts>
    </asp:ScriptManager>

Granted, this brings in some ASP.Net Ajax that may ugly things up, but it works for our own javascript files.

2 Comments so far

  1. Masoud on August 1st, 2009

    nice job.

    it’s usefull for me ;)

  2. Nick on July 1st, 2010

    Thanks! I was having problems with the first option and then I found your blog and used the second option with success.

Leave a Reply