4

I want to include a javascript file like so

<script type="text/javascript" runat="server" src="~/file.js"></script>

The idea is that I want to include the file.js via relative path instead of an absolute path, and I want .NET to figure out the appropriate directory (ie. is it ./ or ../, or ../../ etc...).

But when I try the code above, I get compilation error.

HOw do I properly include a javascript file?

1
  • Are you MVC-ing or vanilla ASP.Net? Commented May 25, 2011 at 20:50

3 Answers 3

7

You can try this...

Razor:

<script type="text/javascript" src="@Url.Content("~/file.js")"></script>

WebForms:

<script type="text/javascript" src="<%=Page.ResolveUrl("~/file.js")%>"></script>
Sign up to request clarification or add additional context in comments.

4 Comments

i get parse error with webforms method : Parser Error Message: Server tags cannot contain <% ... %> constructs.
Sorry, I accidentally left the runat="server" in. As a note, It's been years since I've worked with WebForms.
how i get this error: CS0103: The name 'Url' does not exist in the current context
Ok, try the new example. I didn't realize that Url was an MVC specific thing.
1

Remember that path-'relativity' is most important to the browser. Paths have to be relative to the address of the PAGE you're looking at. That's why controls and master pages that might not be in the same folders as the pages that use them go to lengths to manipulate the paths of resources they include so they work.

So in your case, drop the runat= part and if file.js is at the root of the application you should be good to go.

1 Comment

but if i just include, including from Default.aspx works, but including from subdirectory/Default.aspx doesn't work
0

If you're using MVC you can use

<script type="text/javascript" src="@Url.Content("~/file.js")" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.