3

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).

8
  • under which path is page.html Commented May 10, 2019 at 6:55
  • 2
    because such path does not exist Commented May 10, 2019 at 6:55
  • The question is why it said static/canvas.js instead of /static/script.js ? Commented May 10, 2019 at 6:55
  • If you remove the slash doesn't it work? Or else add .. before it? page.html is in the same folder as static, so when doing /static he might be looking for a folder in page.html Commented May 10, 2019 at 6:59
  • @RadonirinaMaminiaina waht do you mean? The error message does say /static/script.js - in file:///static/canvas.js file:// is the protocol and the target is /static/canvas.js Commented May 10, 2019 at 7:09

3 Answers 3

5

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
    • it is worth mentioning that ./ 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:

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments