简体   繁体   English

包括相对于网站根目录的JS和CSS文件

[英]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. 我正在寻找包含CSS / JS文件的最佳实践,就文件URI而言。 I see people include files both relative from the website root by giving the full URI to the file: 我看到人们通过给文件提供完整的URI来包含来自网站根目录的文件:

<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 ). 但是,如果整个项目中有多个不同位置的文件,那么每次都会有不同的相对路径(对于同一个文件可能会非常混乱),所以在这种情况下绝对可能是首选(为了健壮,你应该这样做)将变量或类似的webroot路径: $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. 在第一种情况下,URI对于网站的域是绝对的。 So, the URI would be: 所以,URI将是:

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: 那么css文件的路径将是:

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

Thus, it depends where are your files located. 因此,它取决于您的文件位于何处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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