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?

Barrosy
  • 1,407
  • 2
  • 25
  • 56

1 Answers1

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.

mason
  • 31,774
  • 10
  • 77
  • 121
  • So basically `@Scripts.Render("~/Scripts/custom.js")` is totally the same as ``. There is no difference, except Razor syntax. – broadband Sep 20 '19 at 16:55
  • 1
    @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 `` syntax. – mason Sep 20 '19 at 16:57
  • Yes, good point. If one would create `page.html` and included `` it wouldn't work. Well, one could use `..\` or full url path. – broadband Sep 20 '19 at 16:59
  • 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 Sep 20 '19 at 18:13
  • @broadband Should be the same - just check the resulting HTML if you want to know for sure. – mason Sep 20 '19 at 18:20