Reputation:
I have this project structure:
/root
/static
script.js
page.html
This code:
<html>
<head>
<script src="/static/script.js"></script>
</head>
<body>
...
</body>
</html>
results in:
Loading failed for the <script> with source “file:///static/script.js”.
Why is that? I would expect it to search for static
folder in current directory (i.e. root
).
Upvotes: 3
Views: 1882
Reputation:
In this particular case the error is produced, because I have just opened page.html
in a browser on my machine (i.e. I have not served it via server), thus /
is interpreted as local machine's root. If I have served the project, then /
would be interpreted as project's root, and there would be no error.
A little more elaborate explanation/illustration.
Given this structure:
/root
/static
script.js
page.html
Here are what different paths (in page.html
) will refer to:
/
— root directory, it might mean /root
, but also might mean the root of current environment (see explanation at the beginning of this answer)./
— current (the one where page.html
resides) directory, it just so happens that it is /root
in this case
./
can be omitted altogether, when referencing some file in current directory; so ./static/script.js
is equivalent to static/script.js
I have derived understanding needed for this answer, from:
Upvotes: 5
Reputation: 19
If you have any directory into your root folder and your js file into that then you have to mention path only with folder name then file name like:
folder-name/filename.js
because into web browser there is no need to add forward slash into starting of file path browser so it by self
Upvotes: 0
Reputation: 849
The error is there because there is no such file in your system's root directory.
This can easily be solved by serving your /root
folder and accessing the page.html
via that server.
You can find a list of static file servers Here.
Going with Node.js
's http-server.
Open a terminal in your '/root' directory and run the following commands:
npm install -g http-server
http-server -p 8000
Then you can access your page.html
file at http://localhost:8000/page.html
Upvotes: 2