Why would a developer place a forward slash at the start of each relative path?

stefmikhail picture stefmikhail · Sep 30, 2011 · Viewed 28.5k times · Source

I am examining some code for a friend, and have found that the developer who built his site began each and every relative src, href, and include with a forward slash /.

For example:

src="/assets/js/jquery.js"

I have never seen this before. So my question is, why would a developer place a forward slash / at the start of a relative path?

Answer

Oded picture Oded · Sep 30, 2011

It's done in order to root the path (making it an absolute path).

It ensures that the path is not relative but read from the root of the site.

This allows one to move a file around and not have to change the links to the different resources.

Using your example:

src="/assets/js/jquery.js"

If the referencing file is in /pages/admin/main.html (for example) using relative paths you would use:

src="../../assets/js/jquery.js"

Suppose you move the file to a child directory. No changes would be needed for with the original rooted path, but the relative one would need to change to:

src="../../../assets/js/jquery.js"