简体   繁体   中英

Including JS and CSS files relative to website root

I'm looking for best practices when including CSS/JS files, in terms of the file URI. I see people include files both relative from the website root by giving the full URI to the file:

<link rel="stylesheet" href="/my/path/to/css/main.css">

I tend to do it this way because I find it easier to know where the file is when I'm reading the code, and I've not come across an issue with it. But I also see a lot of relative includes:

<link rel="stylesheet" href="css/main.css">

Which way do you define the file location and why? Is one better than the other?

I prefer relative includes because they are robust against platform changes (eg deploying from test to live platform) because as long as the internal structure of your project does not change they still will work while absolute paths may break in such cases. Also it's sometimes difficult to know the absolute path while the relative document dependent path is pretty obvious.

However, if you have files in several different places throughout your project, you would have different relative paths each time (for the same file which might be quite confusing), so in this case absolute ones might be preferred (for robustness' sake you should have the webroot path in a variable or similar: $WEBROOT/css/main.css ). It all comes down to your personal needs I guess.

In the first case, the URI is absolute to the website's domain. So, the URI would be:

http://www.example.com/my/path/to/css/main.css

For the second method, the path is relative to the current path. So let's say you are now in

http://www.example.com/store/product/121

Then the path to the css files would be:

http://www.example.com/store/product/css/main.css

Thus, it depends where are your files located.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM