I’ve recently been working on a project and I’ve been seeing two different forms of url’s being used.
src="../MyLinkUrl"
and
src="/MyLinkUrl"
We are using MVC .NET and the times I have seen the .. usages have been in Javascript code files and not when it’s been generated by the MVC URL helpers. Typically the usages range from specifying a controller action to specifying images.
Both seem to work but I’m wondering which is the better practice or if it depends on the context. Some questions I have are:
- What benefits/pitfalls does one have over the other
- Is one better practice than the other
- Does it depend on context and if so what context?
5
When you see /path/to/file
that is an absolute path. Starting from the server’s root, it’s followed down to the file. With just /file
that means that you’re looking directly in the server’s root.
Whenever you do not have a leading slash, the path is taken as relative. This means that, starting from your current point in the file system, you follow the path. ../file
would mean to look in the parent directory for file
. If you had just file
it would look in the current directory.
4
It is probably better to use relative path (../../otherdir/file.html
) as it changes less frequently and you may save on maintenance and refactoring. For instance, correcting some spelling mistake in the folder name will always break the absolute path to that folder but may not break the relative path.
2