What are the pros and cons of referencing web assets using relative or absolute paths? For example:
<link rel="StyleSheet" href="/css/mystylesheet.css" type="text/css" />
<img src="/imag开发者_Go百科es/myimage.gif" alt="My Image" />
vs.
<link rel="StyleSheet" href="../css/mystylesheet.css" type="text/css" />
<img src="../images/myimage.gif" alt="My Image" />
The answer is "it depends". But most of the time, the absolute path is probably best.
I use absolute paths where I am using templating, or if I am using Apache's mod_rewrite.
You might use a relative path if you had a page with an accompanying stylesheet that might be placed at different levels when it gets uploaded. i.e. You've written a page that will be used on many website, and some people might upload it to the root directory and some people might not - by using a relative path, as long as they upload the html file and css file together, it will work - whereas an absolute path wouldn't in this scenario.
It depends on your server side organization of the files. If you use URL rewriting or a front controller than relative paths probably won't work.
On the other hand, if you use absolute paths (and even if you just use "normal" HTML pages) you can rearrange the pages without caring about their location in your structure.
The big issue if you choose to use absolute paths instead of using relative paths is maintainability.
For example, imagine if you want to change the structure of your server files your even move your application to other environments. To do that, you will need extra work, since the change of all your absolute paths is required. For the same scenario, with the usage of relative paths, the extra work is no longer necessary.
My advice is to use relative paths as standard in your development process and only if it is absolutely necessary, choose the usage of absolute paths.
精彩评论