.net - relative url for javascript src?
I want to include a javascript file like so
<script type="text/javascript" runat="server" src="~/file.js"></sc开发者_运维问答ript>
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?
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>
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.
If you're using MVC you can use
<script type="text/javascript" src="@Url.Content("~/file.js")" />
精彩评论