0

Could anyone explain me the difference between:

<script src="/Scripts/custom.js"></script>

and (added tilde symbol)

<script src="~/Scripts/custom.js"></script>

and

@Scripts.Render("~/Scripts/custom.js")

within an ASP.NET MVC application (mainly in Razor View code)?

I am aware that usually @Scripts.Render is used for bundling and minifying scripts. As you can see in my third example, I am not using @Scripts.Render("~/bundles/*") on purpose because I am not making this question look like question that is about bundling. I would like to know what the best way would be for rendering (page specific) scripts. Is there any other significant reason to use one before another?

1 Answer 1

3
<script src="/Scripts/custom.js"></script>

This is relative to the root of your site. It's expecting a custom.js file to be in a Scripts directory in the root of your site, ex: example.com/Scripts/custom.js

<script src="~/Scripts/custom.js"></script>

This is virtual root relative. If your site is hosted as a virtual application in IIS (a sub application), then it will ensure that it looks for a custom.js file in the root of your virtual application, rather than the root of the parent site. So even if your site is hosted at example.com/yoursite, ~/Scripts/custom.js will look for example.com/yoursite/Scripts/custom.js instead of example.com/Scripts/custom.js.

@Scripts.Render("~/Scripts/custom.js")

This looks for the file at the same location as <script src="~/Scripts/custom.js"></script>, but is just using a Razor HTML Helper as a shorthand to generate the HTML markup.

Sign up to request clarification or add additional context in comments.

5 Comments

So basically @Scripts.Render("~/Scripts/custom.js") is totally the same as <script src="~/Scripts/custom.js"></script>. There is no difference, except Razor syntax.
@broadband I think it's important to note that the tilde only works with Razor - it won't work if you have a raw HTML file and use the <script src="~/Scripts/custom.js"></script> syntax.
Yes, good point. If one would create page.html and included <script src="~/Scripts/custom.js"></script> it wouldn't work. Well, one could use `..` or full url path.
Despite this difference, everything else is the same? I'm just looking for yes or no answer. I also tried running few examples and it seems to confirm the equality. I havent looked the source code yet.
@broadband Should be the same - just check the resulting HTML if you want to know for sure.

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.