Is there any difference between ./ and / in <script> src attribute? [duplicate]

孤者浪人 提交于 2019-12-24 16:52:41

问题


Given the following project structure:

/root
  /static
    script.js
  page.html

This will 'import' script.js, into the HTML file:

<html>
    <head>
        <script src="/static/script.js"></script>
    </head>
    <body>
        ...
    </body>
</html>

this will, as well:

<html>
    <head>
        <script src="./static/script.js"></script>
    </head>
    <body>
        ...
    </body>
</html>

I am wondering:

  1. Is one way preferred over the other?
  2. Are there any cases, when / and ./, in she src attribute of <script> will behave differently?

回答1:


Now, I am not super experienced in JavaScript, but I'll let you know what I know.

[...]
<script src="./static/script.js"></script>
[...]
<!--This would reference files in the current folder (where the webpage itself is stored)-->
[...]
<script src="/static/script.js"></script>
[...]
<!--This would reference an absolute path within your webserver, and cannot change dynamically based on from where you load it.-->

Generally speaking, I'd go for ./ when you load it from a file in your current folder (and/or server), whilst doing / seems like an external reference to me, which is also not dynamic. If you happen to move the file (if it was in the same directory as your page), I think JavaScript would also reference the new file instead of complaining about the old one.

I cannot guarantee that any of the info above is correct as I am not a really good JS-Developer, but at least this should help you figure out the syntax a little more.




回答2:


Yes, They both are different. You are not able to see as the index.html is already in your root directory. If there is a .html file inside a directory. Then you can see the difference.

./ This gives a relative path from the file you are accessing it

/ This gives an absolute path from the root of your directory

If this is the directory structure

/root
 /static
  script.js
 /page
  index.html

Then, you won't be able to use ./ as it won't find script folder in the page folder

So, if you have a complex directory structure use ./ i.e. relative path, and if you have a plain structure / i.e. absolute path would be good. For better practice, the relative path is preferred over an absolute path. Hope, this answered your question.




回答3:


./ is a relative path or the current directory where your asset will be served.

/ is an absolute path or the root path from where your asset will be served.




回答4:


./ is a relative path linking to the current directory.

/ is an absolute path linking to the root directory.

You can find more information here.



来源:https://stackoverflow.com/questions/56071759/is-there-any-difference-between-and-in-script-src-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!